如何从字符串中提取特定文本

How to extract certain text from a string

我有这样的字符串:

hi my best friend #John How Are You?

我想从字符串中提取名字:

john

此字符串只有一个名称,它可以是字符串将具有的任意多个名称。我想获取 #[space] 之间的字符串。

我试过使用 explode()foreach() 循环,但我无法获得此值。

$text = "hi my best friend #John How Are You?";

preg_match_all("/(#\w+)/", $text, $matches);

var_dump( $matches );

试试这个

 <?php
$string="hi my best friend #John How Are You?";
preg_match('/(?<=hi my best friend #)\S+/i', $string, $match);
echo $match[0];

输出

Jhon

试试这个,

$string = "hi my best friend #John How Are You?";
$arr = explode(" ",$string);
foreach($arr as $val){
    if (strpos($val,'#') !== false) {
        $result = str_replace("#","",$val);
    }
}
echo $result;

正则表达式会很好,但如果您仍想使用 explode() 和循环来执行此操作,您可以尝试以下代码:-

$str="Hello my name is #John and this is my friend #julia"; $exp=explode(" ",$str);//exploding string from space

foreach($exp as $key=>$val){ if(strpos($val,"#")===false){continue; } else{$new[$k]=str_replace("#","",$val);}

}

print_r($new);

希望这对您有所帮助。

这是一个快速工作的例子

$string = "hi my best friend #John How Are You?";

$explodedstring = explode('#', $string);

$explodedforspace = explode(' ',$explodedstring[1]);

echo $explodedforspace[0];


?>