alex
alex

Reputation: 1711

Replacing Spaces with Underscores

I have a PHP Script that users will enter a name like: Alex_Newton,

However, some users will use a space rather than an underscore, so my question is:

How do I auto-replace spaces with Underscores in PHP?

Upvotes: 168

Views: 284451

Answers (10)

Aleksey Polyanskiy
Aleksey Polyanskiy

Reputation: 1

str_replace - it is evident solution. But sometimes you need to know what exactly the spaces there are. I have a problem with spaces from csv file.

There were two chars but one of them was 0160 (0x0A0) and other was invisible (0x0C2)

my final solution:

$str = preg_replace('/\xC2\xA0+/', '', $str);

I found the invisible symbol from HEX viewer from mc (midnight viewer - F3 - F9)

Upvotes: 0

Thoracius Appotite
Thoracius Appotite

Reputation: 357

Strtr replaces single characters instead of strings, so it's a good solution for this example. Supposedly strtr is faster than str_replace (but for this use case they're both immeasurably fast).

echo strtr('Alex Newton',' ','_');
//outputs: Alex_Newton

Upvotes: 1

blakroku
blakroku

Reputation: 551

You can also do this to prevent the words from beginning or ending with underscores like _words_more_words_, This would avoid beginning and ending with white spaces.

$trimmed = trim($string); // Trims both ends
$convert = str_replace('', '_', $trimmed);

Upvotes: 8

Fil
Fil

Reputation: 8873

I used like this

$option = trim($option);
$option = str_replace(' ', '_', $option);

Upvotes: 0

aksu
aksu

Reputation: 5235

As of others have explained how to do it using str_replace, you can also use regex to achieve this.

$name = preg_replace('/\s+/', '_', $name);

Upvotes: 80

Viktor
Viktor

Reputation: 3536

$name = str_replace(' ', '_', $name);

http://php.net/manual/en/function.str-replace.php

Upvotes: 27

Niklas
Niklas

Reputation: 30002

Use str_replace:

str_replace(" ","_","Alex Newton");

Upvotes: 7

webspy
webspy

Reputation: 726

Call http://php.net/str_replace: $input = str_replace(' ', '_', $input);

Upvotes: 11

anubhava
anubhava

Reputation: 785156

Use str_replace function of PHP.

Something like:

$str = str_replace(' ', '_', $str);

Upvotes: 17

Tim Fountain
Tim Fountain

Reputation: 33148

$name = str_replace(' ', '_', $name);

Upvotes: 426

Related Questions