tags:

views:

72

answers:

4

Hi,

I want to replace leading space with   same number of occurrences i.e.

Bit explanatory :

If one leading space exist in input then it should replace with one  

If two leading spaces exist in input then it should replace with two  

If n leading spaces are exist in input then it should replace with exact n number of times with  

Ex.1:
 My name is XYZ
output:
 My name is XYZ

Ex.2 :
  My name is XYZ
output:
  My name is XYZ

I want to replace only leading spaces, using PHP regex.

Your suggestion are welcome.

Thanks

+3  A: 
$len_before = strlen($str);
$str = ltrim($str, ' ');
$len_after = strlen($str);
$str = str_repeat(' ', $len_before - $len_after) . $str;

Using preg_replace there is also

$str = preg_replace('/^( +)/e', 'str_repeat(" ", strlen("$1"))', $str);

but note that it uses the /e flag.

See http://www.ideone.com/VWNKZ for the result.

KennyTM
thats not regex.
Talvi Watia
that is not Regexp, but it is the best way and less heavy! +1
CuSS
Don’t forget the *m* flag to have `^` match the begin of a line.
Gumbo
+1  A: 

Use:

preg_replace('/^ +/m',' ',$str);

You can test it here

Sarfraz
+1 simple and objective answer
CuSS
The objective is to replace *each* of the leading spaces with ` `. You're replacing *all* of them with *one* ` `.
Alan Moore
@alan you are right. my bad... I hate slashes for delimiters, btw, why I use `#`..
Talvi Watia
+5  A: 
preg_replace('/\G /', ' ', $str);

\G matches the position where the last match ended, or the beginning of the string if there's no previous match.

edit: Actually, in PHP it matches where the next match is supposed to begin. That isn't necessarily the same as where the previous match ended.

Alan Moore
+1 simple and objective answer
CuSS
@All : Thanks folks for your response.@Alan : I followed your approach.I just wanted to know for better approach to follow which one is optimum, efficient among flag 'G', 'm' and 'e', so that i'll hv actual reason to use mentioned flags
pravin
Well, `m` allows the `^` to match at the beginning of a line as well as at the beginning of the string, so it's not relevant in this case. `e` causes the replacement to be treated as code instead of as a static string. That could get very expensive indeed, but in practice the code is usually short and quick. Even so, `\G` will usually be the most efficient option.
Alan Moore
@Alan: Thanks :)
pravin
A: 

Use preg_match with PREG_OFFSET_CAPTURE flag set, the offset is the length of the "spaces". Then use str_repeat with the offset.

a110y