Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Character Replacement

Status
Not open for further replies.

W0nkey

Programmer
Joined
Jul 16, 2004
Messages
6
Location
GB
I am taking a string and trying to convert it into a url friendly version. In short, I need spaces changed to "_" and only letters and numbers. e.g "Special's Menu Today?" -> "Specials_Menu_Today.html"

I can use str_replace for some parts or make an array of valid/invalid characters, but I'd like to hear suggestions on how to do this 'nicely'. Is there a built in function that can do this easily?

Thanks.
 
I should have mentioned, I think ereg or preg look like the way to achieve this, but I'm a bit stuck on writing the regular expression ...
 
You could set up a loop around the string and check each character e.g.

for each char in string as ic
if ic==" " then ic = "_";
if ic between (a..z) then oc=ic;
if ic between (0..9) then oc=ic;
if ic between (A..Z) then oc=ic;
next

or something like that, you might convert the character to its character code and test that (remember a-z is a dense set in ascii).
The implementation is left as an excersize for the reader !
 
rudely plaigiarised(sic) from PHP.net
Code:
<?php
$string = "Special's Menu Today?";

$patterns[0] = "/'/";
$patterns[1] = "/ /";
$patterns[2] = "/?/";

$replacements[0] = "";
$replacements[1] = "_";
$replacements[2] = "";

echo preg_replace($patterns, $replacements, $string);
?>

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
I suggest looking into the urlencode function.

The php definition is:
string urlencode ( string str)

so, you could do:
$urlfriendly = urlencode($noturlfriendly)

This function will replace any space or symbol with the url version (ie: space becomes %20, etc.)

Not sure if this is what you're looking for, but check it out.

*cLFlaVA
----------------------------
A polar bear walks into a bar and says, "Can I have a ... beer?"
The bartender asks, "What's with the big pause?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top