Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.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 麻烦添加http://mainserver/ 对所有人(href | action | src)=,给我添麻烦吧!_Php_Html_Regex - Fatal编程技术网

Php 麻烦添加http://mainserver/ 对所有人(href | action | src)=,给我添麻烦吧!

Php 麻烦添加http://mainserver/ 对所有人(href | action | src)=,给我添麻烦吧!,php,html,regex,Php,Html,Regex,我有这个网址 $output = "href=\"/one/two/three\" href=\"one/two/three\" src=\"windows.jpg\" action=\"http://www.google.com/docs\""; 应用正则表达式时: $base_url_page = "http://mainserver/"; $output = preg_replace( "/(href|src|action)(\s*)=(\s*)(\"|\')(\/+|\/*)(.*)(

我有这个网址

$output = "href=\"/one/two/three\"
href=\"one/two/three\"
src=\"windows.jpg\"
action=\"http://www.google.com/docs\"";
应用正则表达式时:

$base_url_page = "http://mainserver/";
$output = preg_replace( "/(href|src|action)(\s*)=(\s*)(\"|\')(\/+|\/*)(.*)(\"|\')/ismU", "$1=\"" . $base_url_page . "$6\"", $output );
我明白了:

$output = "href=\"http://mainserver/one/two/three\"
href=\"http://mainserver/one/two/three\"
src=\"http://mainserver/windows.jpg\"
action=\"http://mainserver/http://www.google.com/docs\"";
如何修改正则表达式以防止出现这种情况:???

试试看

$output = preg_replace( "/(href|src|action)\s*=\s*["'](?!http)\/*([^"']*)["']/ismU", "$1=\"" . $base_url_page . "$2\"", $output );

我简化了您的正则表达式,并添加了一个前瞻,确保您匹配的字符串不以
http
开头。现在,这个正则表达式既不允许在URL中使用单引号,也不允许在URL中使用双引号。

关于使用正则表达式解析HTML的一些建议:只使用更改基URI就足够了吗?这将不允许包含像
href=”这样的纯
属性值。”http://example.com/foo“bar”
(这是一个有效的URI!)。我知道,这就是为什么我在回答中这样写道。如果这是OP的问题,可以更改正则表达式。此解决方案非常好,谢谢。。。只有当href=“/url”。。。我们将得到以下结果:href=-->/??(在我的正则表达式中,我使用:(\/+\124;\/*))解决了这个问题……。我不确定我是否遵循了-像
href=“/URL/foo”
这样的URL将被转换为
http://mainserver/url/foo
在我的测试中。这是错的吗?你能不能用一个目前效果不如预期的例子来编辑你的问题?
$output = preg_replace( "/(href|src|action)\s*=\s*[\"'](?!http)(\/+|\/*)([^\"']*)[\"']/ismU", "$1=\"" . $base_url_page . "$3\"", $output );