Jump to content

Finding spaces in a string


tcorbeil

Recommended Posts

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

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"

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.