Forum Moderators: coopster
I have a regular expressions problem I cannot seem to figure out with my limited knowledge of the subject.
I have a web page with a number of URL's and would like to replace spaces with underscores using regular expressions in PHP like this for example:
[example.com...] page/
becomes [example.com...]
Any ideas?
Thank you in advance,
Ron
So you have something like:
blah blah blah <a href="http://example.com/page 7>old page</a> blah blah blah or <a href="http://example.com/page 2354>new page</a>
Is that the situation? In that case
function stripSpaces ($matches)
{
return $matches[1] . str_replace(' ', '_', $matches[2]);
}
$pattern = '/(href=")([^"]+)/i';
$new = preg_replace_callback($pattern, "stripSpaces", $string);
'/(<a href=)([^>]+)/i'
If you just have a list of URLs each on its own line, then that's fairly simple too. The your pattern could look like this
$pattern = '`(http://)(.*)`i'; // back ticks b/c of / in pattern
If you have something like this though
blah blah blah [example.com...] 7/ is a good page
You're in trouble since you would need artificial intelligence to know where the URL is supposed to end unless they all terminate with something known that won't appear elsewhere (like ".htm" or ".php").