I have a custom PHP website for my blog system. I want to replace my all space from the user name with an underscore using PHP script.

Please suggest to me the best way to replace spaces with underscores.

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

php 

Nov 17

3 Answers

you can use str_replace() achieve this.

Syntax : 

str_replace(find,replace,string,count);

Parameter : 

  • find : Specifies the value to find
  • replace : Specifies the value to replace the value in find
  • string : Specifies the string to be searched
  • count : A variable that counts the number of replacements

Example : 

$string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
$string = str_replace(' ', '_', $string);
echo $string; // Lorem-Ipsum-is-simply-dummy-text-of-the-printing-and-typesetting-industry.

answered Dec 02


string replace space with underscore PHP code example

Example 1: PHP replace space with underscore

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

Example 2: PHP convert spaces to underscores

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

answered Dec 30


preg_replace() returns an array if the subject the parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or null if an error occurred.

Example #1 Using backreferences followed by numeric literals

<?php
	$string = 'April 15, 2003';
	$pattern = '/(\w+) (\d+), (\d+)/i';
	$replacement = '${1}1,$3';
	echo preg_replace($pattern, $replacement, $string);
?>

The above example will output:

April1,2003

Example #2 Using indexed arrays with preg_replace()

<?php
	$string = 'The quick brown fox jumps over the lazy dog.';
	$patterns = array();
	$patterns[0] = '/quick/';
	$patterns[1] = '/brown/';
	$patterns[2] = '/fox/';
	$replacements = array();
	$replacements[2] = 'bear';
	$replacements[1] = 'black';
	$replacements[0] = 'slow';
	echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The bear black slow jumps over the lazy dog.

By ksorting patterns and replacements, we should get what we wanted.

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

The above example will output:

The slow black bear jumps over the lazy dog.

answered Dec 30


Login and Submit Your Answer
Browse other questions tagged  php or ask your own question.