PHP - 仅在文本链接中将空间转换为%20

时间:2012-06-21 17:46:09

标签: php regex

我有一个包含超链接的文本,一些超链接包含空格,我想将它们转换为%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*)?/

非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:4)

最简单的方法是使用DOMDocumentlet 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>

答案 1 :(得分:3)

这里的正确答案不是正则表达式。这是urlencode()http://php.net/manual/en/function.urlencode.php