faqts : Computers : Programming : Languages : PHP : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

108 of 115 people (94%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How do I replace all sequences of multiple spaces in a string with a single space? str_replace gives error when I try replace any 2 chars w/ 1 char

Aug 24th, 2000 22:30
Ben Udall, Dave Parizek, http://www.php.net/manual/function.ereg-replace.php


This can be easily done using regular expressions and the ereg_replace 
function.
// Replaces one or more spaces with a single space
$new_str = ereg_replace(" +", " ", $str);
// Replaces one or more spaces or tab characters with a single space
$new_str = ereg_replace("[ \t]+", " ", $str);
// Replaces any sequence of spaces, tabs, and or new-line characters
// with a single space
$new_str = ereg_replace("[ \t\r\n]+", " ", $str);