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. Link to comment https://forums.phpfreaks.com/topic/43976-finding-spaces-in-a-string/ 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); Link to comment https://forums.phpfreaks.com/topic/43976-finding-spaces-in-a-string/#findComment-213502 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" Link to comment https://forums.phpfreaks.com/topic/43976-finding-spaces-in-a-string/#findComment-213506 Share on other sites More sharing options...
tcorbeil Posted March 23, 2007 Author Share Posted March 23, 2007 Thanks mjlogan. Works like a charm! Link to comment https://forums.phpfreaks.com/topic/43976-finding-spaces-in-a-string/#findComment-213507 Share on other sites More sharing options...
tcorbeil Posted March 23, 2007 Author Share Posted March 23, 2007 Gotcha obsidian. Thanks. Link to comment https://forums.phpfreaks.com/topic/43976-finding-spaces-in-a-string/#findComment-213510 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.