Maximus
Maximus

Reputation: 2976

PHP - Convert space into %20 only in links from text

I have a text which contains hyperlinks, some hyperlinks contain spaces and I want to convert them into %20.

For example:

To make hyperlinks <a href="http://www.link-to-my-page.com/page 1.html">Page 1</a>

If I convert above text using rawurlencode function it returns

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

I wrote following RE to convert space into %20 in links only but I am not sure how to apply space (\s)* with preg_replace.

/(http|https|ftp|ftps)(\:\/\/[a-zA-Z0-9\-\.]+)(\s)*\.[a-zA-Z]{2,4}(\/\S*)?/

Any help would be greatly appreciated.

Thanks

Upvotes: 2

Views: 1190

Answers (2)

nickb
nickb

Reputation: 59709

The easiest thing to do is to use DOMDocument and 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;

Output, thanks to this SO question:

To make hyperlinks <a href="http://www.link-to-my-page.com/page%201.html">Page 1</a>

Upvotes: 4

hsanders
hsanders

Reputation: 1898

The right answer here isn't a regexp. It's urlencode() http://php.net/manual/en/function.urlencode.php

Upvotes: 3

Related Questions