Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要替换模式的PHP文档_Php_Search_Replace_Pattern Matching_Domdocument - Fatal编程技术网

要替换模式的PHP文档

要替换模式的PHP文档,php,search,replace,pattern-matching,domdocument,Php,Search,Replace,Pattern Matching,Domdocument,我需要找到并替换超链接的http链接。这些http链接位于span标记内 $text具有html页面。其中一个span标记有如下内容 <span class="styleonetwo" >http://www.cnn.com/live-event</span> 它在regexpal中提供的regextster中工作得非常好。当我在PHP代码中使用相同的模式时,我得到了大量奇怪的错误。我得到了未知的修改错误,甚至转义字符!以下是我的preg_replace代码 $http

我需要找到并替换超链接的http链接。这些http链接位于span标记内

$text具有html页面。其中一个span标记有如下内容

<span class="styleonetwo" >http://www.cnn.com/live-event</span>
它在regexpal中提供的regextster中工作得非常好。当我在PHP代码中使用相同的模式时,我得到了大量奇怪的错误。我得到了未知的修改错误,甚至转义字符!以下是我的preg_replace代码

$httpRegex = '/\b(\?:(\?:https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#/%\?=~_|$!:,.;]*[-A-Z0-9+&@#/%=~_|$]/';
$cleanText = preg_replace($httpRegex, "<a href='$0'>$0</a>", $text);
$httpRegex='/\b(\?:(\?:https?| ftp |文件):\/\/\/|(www | ftp)\)[-A-Z0-9+&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;
$cleanText=preg_replace($httpRegex,“,$text);

我对“未知修饰符”感到非常失望,于是继续使用DOMDocument来解决我的问题。

正则表达式很适合这个问题-所以最好使用
preg\u replace

现在您的模式中只有几个未转义的字符,所以请转义它们或选择另一个字符作为分隔符-例如,
^
。因此,正确的模式是:

$httpRegex = '^\b(?:(?:https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#\/%\?=~_|$!:,.;]*[-A-Z0-9+&@#\/%=~_|$]^i';

preg_replace()有什么问题吗??菲尔,我更新了问题。谢谢。你的正则表达式没有逃过。您必须转义转义字符和分隔符!谢谢你,尼基塔!这很有帮助。当我进行preg_替换时($httpRegex,“,$text);它给了我一个没有“http”的链接。我可以用preg_replace($httpRegex,“http://$0”,$text)替换代码;但是,如果文本中的链接是
code
code
,它会给我
code
。我可以有像
code
wwww.link.com
code
code
link.com
code
这样的链接。我需要写两个正则表达式来解决这个问题吗?再次感谢。我将使用一个
preg\u replace\u回调函数
——下面是一个示例:
\b(?:(?:https?|ftp|file)://|(www|ftp)\.)[-A-Z0-9+&@#/%?=~_|$!:,.;]*[-A-Z0-9+&@#/%=~_|$]
$httpRegex = '/\b(\?:(\?:https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#/%\?=~_|$!:,.;]*[-A-Z0-9+&@#/%=~_|$]/';
$cleanText = preg_replace($httpRegex, "<a href='$0'>$0</a>", $text);
$httpRegex = '^\b(?:(?:https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#\/%\?=~_|$!:,.;]*[-A-Z0-9+&@#\/%=~_|$]^i';