Php 如何从字符串中提取特定文本
我喜欢这样的字符串:Php 如何从字符串中提取特定文本,php,string,substring,Php,String,Substring,我喜欢这样的字符串: 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
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];
试试这个
$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()和loop执行此操作,则可以尝试以下代码:- 你好,我的名字是约翰,这是我的朋友朱莉娅代码>
$exp=explode(“,$str”)//从空间分解字符串
foreach($exp as$key=>$val){
if(strpos($val,“#”)===false){continue;
}
else{$new[$k]=str#u replace(“#“,”,$val);}
}
print\r($new)代码>
希望这对您有所帮助。这里是一个快速工作的示例
$string = "hi my best friend #John How Are You?";
$explodedstring = explode('#', $string);
$explodedforspace = explode(' ',$explodedstring[1]);
echo $explodedforspace[0];
?>
非常感谢您的快速回复。这对我很有帮助,非常感谢。谢谢维诺的快速回复。我真的很感激。非常感谢您的快速回复。我真的很感激。非常感谢您的回复。这只适用于第一个元素。如果有多个名称带有#tag::---@user3227262,您必须运行循环。非常感谢您的回复。我真的很感激。我用preg_match$text=“嗨,我最好的朋友,约翰,你好吗?”找到了解决方案;preg_match_all(“/(#\w+/”,$text,$matches)$把名字还给我。如果它是multiple,那么如果它是multiple,那么它就是$matched数组中唯一的一个元素。然后我在用户名的帮助下在用户配置文件页面上循环并创建链接。非常感谢你的帮助,兄弟。
$string = "hi my best friend #John How Are You?";
$explodedstring = explode('#', $string);
$explodedforspace = explode(' ',$explodedstring[1]);
echo $explodedforspace[0];
?>