正则表达式导致“分隔符不得为字母数字或反斜杠”。 [英] Regex results in "Delimiter must not be alphanumeric or backslash"
问题描述
我有此代码
function a($menu_item, $remove_link) {
$pattern = 'class="(.+)"(.+)<a.+>(.+)</a>';
if($remove_link) {
return preg_replace($pattern, 'class="$1 selected"$2$3', $menu_item); //<- line 6
}
return $menu_item;
}
基本上检查 $ remove_link
为true,然后删除链接并将类定义添加到 $ menu_item
Which basically checks if $remove_link
is true, and then removes the link and adds a class definition to $menu_item
如果我使用
$menu_item = '<li class="menuitem first"><a href="index.php">Home</a></li>';
$menu_item = a($menu_item, true);
应该返回
<li class="menuitem first selected">Home</li>;
正则表达式已经过测试,可以在Notepad ++中使用,但是我的函数给出了这个错误:
The regex is tested and it works in Notepad++, but my function is giving this error:
Warning: preg_replace(): Delimiter must not be alphanumeric or backslash in functions.php on line 6
我看到php模式必须用斜杠定界,所以我尝试使用 class = /(.+)(。+)< a。+>(。+)/< / a>
,但是它给出了相同的错误。
I saw that php patterns have to be "delimited" with slashes, so i tried to use class="/(.+)"(.+)<a.+>(.+)/</a>
instead, but it gives the same error.
我想念什么?我如何正确使用定界符?
What am i missing? How do i use delimiters properly?
推荐答案
您必须在模式的开头和结尾放置模式定界符,例如:
you must put pattern delimiters at the begining and at the end of the pattern, example:
$pattern = '#class="(.+)"(.+)<a.+>(.+)</a>#';
这里#
比 /
,因为可以避免转义模式中的所有斜线,但是可以这样写:
Here #
is a better choice than /
because you avoid to escape all the slashes inside your pattern, but you can write:
$pattern = '/class="(.+)"(.+)<a.+>(.+)<\/a>/';
作为一个注释,您的模式将导致许多回溯:
As an aside comment, your pattern will cause many backtracks:
$pattern = '~class="([^"]+)"([^>]*>)<a[^>]+>([^<]+)</a>~';
会更好。
请记住, +
和 *
是
如果我使用受限字符类而不是点,则可以停止量词的贪婪,例如
If I use a restricted character class instead of the dot, I can stop the greediness of the quantifiers, example
[^] +
接受除
,因此在找到
时停止。
[^"]+
take all characters except "
, thus it stop when a "
is find.
演示:
<?php
function a($menu_item, $remove_link) {
//$pattern = '~class="(.+)"(.+)<a.+>(.+)</a>~';
$pattern = '~class="([^"]+)"([^>]*>)<a[^>]+>([^<]+)<\/a>~';
if($remove_link) {
return preg_replace($pattern, 'class="$1 selected"$2$3', $menu_item);
}
return $menu_item;
}
$menu_item = '<li class="menuitem first"><a href="index.php">Home</a></li>';
echo a($menu_item, true);
这篇关于正则表达式导致“分隔符不得为字母数字或反斜杠”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!