PHP preg_replace: PHP Error[2]: preg_replace():分隔符不能是字母数字或反斜


PHP preg_replace: PHP Error[2]: preg_replace(): Delimiter must not be alphanumeric or backslash

尝试替换字符串一次,得到此错误将非常感谢任何帮助。

$link = '<a href="'.$url.'" title="'.$anchor.'">'.$anchor.'</a> ';
$text = preg_replace(/" ".$anchor." "/,"", $text,1);

得到这个错误信息:

Error[2]: preg_replace(): Delimiter must not be alphanumeric or backslash

任何想法?我想要的只是用链接

替换文本的第一个出现
$link = '<a href="'.$url.'" title="'.$anchor.'">'.$anchor.'</a> ';
$text = preg_replace("/ ".$anchor." /" ,"" , $text , 1 );
// If the spaces were intended
// OR
$text = preg_replace("/".$anchor."/" ,"" , $text , 1 );
// If you do not mean for the anchor to have a space before and after it.

这些正则表达式段必须是字符串或字符串数组

您应该使用不同的分隔符,并且在这种情况下还可以利用双引号:

$text = preg_replace("~$anchor~", $link, $text, 1);

前面的错误是由于您的语法无效或$anchor本身包含正斜杠引起的。(这需要避免。现在使用~作为分隔符,$anchor可能不包含分隔符。

我觉得你是想这么做;

$text = "lorem ipsum dolor";
$anchor = "ipsum";
$link = '<a href="/foobar" title="'.$anchor.'">'.$anchor.'</a>';
$text = preg_replace('/'.preg_quote($anchor, '/').'/', $link, $text, 1);
echo $text;
#=> lorem <a href="/foobar" title="'.$anchor.'">'.$anchor.'</a> dolor

在tehplayground.com上看到它的工作

如果$anchor可能包含一些需要作为regex模式转义的字符,则需要使用preg_quote()