我有一个包含超链接的文本,一些超链接包含空格,我想将它们转换成 %20。
例如:
制作超链接<a href="http://www.link-to-my-page.com/page 1.html">Page 1</a>
如果我使用 rawurlencode 函数转换上面的文本,它会返回
To%20make%20hyperlinks%20%3Ca%20href%3D%22http%3A%2F%2Fwww.link-to-my-page.com%2Fpage%201.html%22%3EPage%201%3C%2Fa%3E
我写了以下 RE,仅在链接中将空间转换为 %20,但我不确定如何使用 preg_replace 应用空间 (\s)*。
/(http|https|ftp|ftps)(\:\/\/[a-zA-Z0-9\-\.]+)(\s)*\.[a-zA-Z]{2,4}(\/\S*)?/
如有任何帮助,我们将不胜感激。
谢谢
最佳答案
最简单的方法是使用 DOMDocument和 let it fix this for you :
$html = 'To make hyperlinks <a href="http://www.link-to-my-page.com/page 1.html">Page 1</a>';
$doc = new DOMDocument();
$doc->loadHTML( $html);
// Save the fixed HTML
$innerHTML = '';
foreach( $doc->getElementsByTagName('p')->item(0)->childNodes as $child) {
$innerHTML .= $doc->saveHTML($child);
}
echo $innerHTML;
输出,thanks to this SO question :
To make hyperlinks <a href="http://www.link-to-my-page.com/page%201.html">Page 1</a>
关于PHP - 仅在来自文本的链接中将空格转换为 %20,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143798/