如果我有一串文字,例如:
<p>Hello world here is the latest news ##news?123## or click here to read more</p>
我想查看字符串并查找以##news?
开头的任何内容然后我想保存它并将id 123
和尾随哈希作为变量,因此最终输出将是:
$myvar == "##news?123##"
如何使用PHP读取输入字符串并将该特定部分保存为变量?
答案 0 :(得分:2)
preg_match
是您遇到此类问题的朋友。
$str='<p>Hello world here is the latest news ##news?123## or click here to read more';
$pttn='@(##news\?(\d+)##)@';
preg_match( $pttn, $str, $matches );
$myvar=$matches[0];
$id=$matches[2];
echo $myvar.' '.$id;
答案 1 :(得分:1)
假设您没有尝试解析HTML,但正如您所说,只是找到以“## news?”开头的任何事件?那么你可以在这里愉快地使用正则表达式:
$string = '<p>Hello world here is the latest news ##news?123## or click here to read more';
$matches = array();
preg_match_all("/(##news\?.*?)\s/",$string,$matches);
print_r($matches);