尝试替换字符串一次,得到此错误将非常感谢任何帮助。
$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()
。