Php preg“替换全部”_&引用;仅通过url中的空格
我有一个html文件,其中包含一些数据,包括一些URL 仅在这些URL上,我想用空格(通过php文件)替换Php preg“替换全部”_&引用;仅通过url中的空格,php,regex,url,preg-replace,Php,Regex,Url,Preg Replace,我有一个html文件,其中包含一些数据,包括一些URL 仅在这些URL上,我想用空格(通过php文件)替换\ucode>字符 这样的url: </p><p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this_is_an_example.html">How_to_sample.</a> 谢谢 编辑: 感谢您的preg\u replac
\ucode>字符
这样的url:
</p><p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this_is_an_example.html">How_to_sample.</a>
谢谢
编辑:
感谢您的preg\u replace\u callback
建议,这就是我要找的
// search pattern
$pattern = '/href="http:\/\/10.20.0.30:1234\/index.php\/(.*?).html">/s';
// the function call
$content2 = preg_replace_callback($pattern, 'callback', $content);
// the callback function
function callback ($m) {
print_r($m);
$url = str_replace("_", " ", $m[1]);
return 'href="http://10.20.0.30:1234/index.php/'.$url.'.html">';
}
更老更明智:不要使用正则表达式-这不是必需的,而且它可能会不稳定,因为正则表达式不知道DOM。使用HTML解析器隔离)
输出:
<p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this%20is%20an%20example.html">How_to_sample.</a></p>
</p><p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this is an example.html">How_to_sample.</a>
使用preg\u replace\u回调
来匹配URL,然后在回调中用str\u replace
(不要对静态字符串使用正则表达式…)替换\u
,这样就可以了。我在示例数据中没有看到任何不合格的下划线。我的意思是,看起来替换所有下划线是安全的。请更新您的输入,让我代表您的情况。preg_replace_回调正是我要找的!谢谢。答案不应作为问题的编辑发布。这不是问答的工作方式。是的,你是对的,但我不能正确地给出答案。我收到一条警告消息说我没有权限。
$html = <<<HTML
<p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this_is_an_example.html">How_to_sample.</a></p>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach($dom->getElementsByTagName('a') as $a) {
$a->setAttribute('href', str_replace('_', '%20', $a->getAttribute('href')));
}
echo $dom->saveHTML();
<p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this%20is%20an%20example.html">How_to_sample.</a></p>
$input = '</p><p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this_is_an_example.html">How_to_sample.</a>';
$pattern = '~(?:\G|\Qhttp://10.20.0.30:1234/index.php\E[^_]+)\K_([^_.]*)~';
echo preg_replace($pattern, " $1", $input);
</p><p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this is an example.html">How_to_sample.</a>
$pattern = '~(?:\G(?!^)|\Qhttp://10.20.0.30:1234/index.php\E[^_]+)\K_([^_.]*)~';