在字符串中查找php字符串并另存为变量

时间:2015-10-26 16:20:29

标签: php

如果我有一串文字,例如:

<p>Hello world here is the latest news ##news?123## or click here to read more</p>

我想查看字符串并查找以##news?开头的任何内容然后我想保存它并将id 123和尾随哈希作为变量,因此最终输出将是:

$myvar == "##news?123##"

如何使用PHP读取输入字符串并将该特定部分保存为变量?

2 个答案:

答案 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);