tcorbeil Posted March 23, 2007 Share Posted March 23, 2007 Hello gain. I am now looking for a way to go through a string variable, find any space that is present and replace it with _. How would I go about? The reason is I get input from a user.. lets say he/she loads a variable $Hockey = "Edmonton Oilers"; this variable is used to create a new webpage but of course, the web does not like spaces.. hence I would need this variable to be $Hockey = "Edmonton_Oilers"; Any help would be much appreciated. T. Quote Link to comment Share on other sites More sharing options...
mjlogan Posted March 23, 2007 Share Posted March 23, 2007 $string = str_replace(" ", "_", $string); or replace anything that is not a character with an underscore so, +_)(*&^%$#@~!{}|:">?<,/.';\[] $string = ereg_replace("[^[:alpha:]]", "_", $string); Quote Link to comment Share on other sites More sharing options...
obsidian Posted March 23, 2007 Share Posted March 23, 2007 If you're wanting to replace tab characters and newlines as well (assuming they may have copied and pasted from another location), you'll need to be more generic with your spacing matches: <?php $string = preg_replace('|\s+|', '_', $string); ?> This will also interpret multiple spaces within the string to a single underscore so you don't end up with "Edmonton_____Oilers" Quote Link to comment Share on other sites More sharing options...
tcorbeil Posted March 23, 2007 Author Share Posted March 23, 2007 Thanks mjlogan. Works like a charm! Quote Link to comment Share on other sites More sharing options...
tcorbeil Posted March 23, 2007 Author Share Posted March 23, 2007 Gotcha obsidian. Thanks. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.