Forum Moderators: coopster

Message Too Old, No Replies

preg_replace

         

rfontaine

9:56 pm on Sep 20, 2004 (gmt 0)

10+ Year Member



How would I use preg_replace to remove all spaces from the URL's on a page and replace them with dashes?

hiker_jjw

10:06 pm on Sep 20, 2004 (gmt 0)




Try something like this to your URLs:

$new_url = preg_replace("/\s/", "-", $url);

hughie

10:08 pm on Sep 20, 2004 (gmt 0)

10+ Year Member



This should do the job

$text="This is a test";

$nospaces_text = preg_replace("/[\s]/","-",$text);

// should echo out "This-is-a-test";
echo $nospaces_text;

hughie

10:09 pm on Sep 20, 2004 (gmt 0)

10+ Year Member



I am too slow, thats the third time in a week ;-)

rfontaine

10:41 pm on Sep 20, 2004 (gmt 0)

10+ Year Member



Yes, but the problem is I have a long string of text with URLS sprinkled in. like;

blah blah blah URL blah blah ....URL blah blah URL .....

So how do I just change the URL's?

Timotheos

11:17 pm on Sep 20, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is there anything that distinguishes the URL in the text. Like do they all have anchor tags? Do they all start with 'http://' or 'www' and end with a known extension like 'html' or 'php'? I'm trying to figure out what kind of flags we could be looking for.

mincklerstraat

11:19 pm on Sep 20, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



give this a go :
function dashreplace($matches) {
return str_replace(' ', '-', $matches[1]);
}
$replacedhtml = preg_replace_callback('#("http://[^"]*)#', 'dashreplace', $yourhtml);

Don't know why you have spaces in your url's. This is an attempt at replacing all those within double quotes "http://[...]" - and not, e.g., those just in ordinary text - reason being that if you've got spaces in your url's, how do you tell from [this...] . com / some kind of url . html from ordinary text? unless you mean urlencoded spaces like %20 or whatever, but that's a different story.

Didn't try this regex out, check it first, I often make mistakes. Function declaration necessary since this is a callback function.

hiker_jjw

11:34 pm on Sep 20, 2004 (gmt 0)



This outta do the trick...

$html = preg_replace("/(href[\s\n\r\t]*=[\s\n\r\t]*[\'\"])([^\'\"]{3,})([\'\"])/ie", "\"$1\".str_replace(\" \", \"-\", \"$2\").\"$3\"", $html);

Believe it or not. I'm not going to bother explaining it, LOL. Trust me, it works. I just did a quick test and it worked.

rfontaine

12:44 pm on Sep 21, 2004 (gmt 0)

10+ Year Member



Yeah, very strange. Somehow I have alot of files where the dashes in the urls got changed to spaces. Hikers method seems to be working well!