preg_match PHP的问题

preg_match PHP的问题,php,preg-match,Php,Preg Match,我有一个字符串: $str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)"; (number)和(/number)充当标签,从字符串中提取特定内容 我有一个preg_match来删除内容: if(preg_match('/(94896)\"(.*)\"(\/94896)/',$str,$c)) {e

我有一个字符串:

$str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)";
(number)
(/number)
充当标签,从字符串中提取特定内容

我有一个
preg_match
来删除内容:

if(preg_match('/(94896)\"(.*)\"(\/94896)/',$str,$c)) {echo "I found the content, its:".$co[1];} 
现在由于某种原因,它在字符串(
$str
)中找不到匹配项,尽管它显然在那里


你知道我做错了什么吗?

你需要从正则表达式字符串中去掉双引号,因为它们不会出现在$str中,但是正则表达式需要它们

'/(94896)\"(.*)\"(\/94896)/'
//       ^^    ^^
//        These aren't in the string.
编辑:我认为您还需要避开括号,因为它们将被解读为分组运算符,而不是实际的括号

你的表达应该是:

'/\(94896\)(.*)\(\/94896\)/'

您需要从正则表达式字符串中去掉双引号,因为它们不出现在$str中,但正则表达式需要它们

'/(94896)\"(.*)\"(\/94896)/'
//       ^^    ^^
//        These aren't in the string.
编辑:我认为您还需要避开括号,因为它们将被解读为分组运算符,而不是实际的括号

你的表达应该是:

'/\(94896\)(.*)\(\/94896\)/'

在正则表达式中使用括号表示子模式。如果要在字符串中搜索这些字符,必须对其进行转义:

preg_match('/\(94896\)(.*)\(\/94896\)/',$str,$c)
如果找到该模式:

echo "I found the content, its:".$c[0];

哦,正如Karl Nicoll所说,为什么在您的模式中使用引号?

在正则表达式中使用括号来表示子模式。如果要在字符串中搜索这些字符,必须对其进行转义:

preg_match('/\(94896\)(.*)\(\/94896\)/',$str,$c)
如果找到该模式:

echo "I found the content, its:".$c[0];
哦,正如卡尔·尼科尔(Karl Nicoll)所说,为什么在您的模式中有引用?

要匹配所有内容:

$str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)";

$re = '/\((\d+)\)(.*)\(\/\1\)/';
preg_match_all($re, $str, $matches,PREG_SET_ORDER);
var_dump($matches);
编号将在
$matches[*][1]
中,内容将在
$matches[*][2]
中,以匹配所有内容:

$str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)";

$re = '/\((\d+)\)(.*)\(\/\1\)/';
preg_match_all($re, $str, $matches,PREG_SET_ORDER);
var_dump($matches);

数字将位于
$matches[*][1]
中,
$matches[*][2]
中的内容双反斜杠将使引擎在该位置查找文字反斜杠。转义只需要一个反斜杠。@MarcB-我讨厌PHP。它应该是带有双反斜杠的字符串,或者是带有单反斜杠的斜杠分隔字符串(如JavaScript或Ruby),但PHP是带有单反斜杠的字符串。它让我晚上睡不着,真的。双反斜杠会让引擎在那个位置上寻找一个字面上的反斜杠。转义只需要一个反斜杠。@MarcB-我讨厌PHP。它应该是带有双反斜杠的字符串,或者是带有单反斜杠的斜杠分隔字符串(如JavaScript或Ruby),但PHP是带有单反斜杠的字符串。它让我晚上睡不着,真的。