开发者

Replace the leading space with   with the same number of times using a PHP regular expression

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

Explanation:

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

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

If n leading spaces are exist in the input then it should replace it with exac开发者_C百科tly n number of times with  .

Example 1:

My name is XYZ

Output:

 My name is XYZ

Example 2:

  My name is XYZ

Output:

  My name is XYZ

How can I replace only leading spaces, using a PHP regular expression?


preg_replace('/\G /', ' ', $str);

\G matches the position where the last match ended, or the beginning of the string if there isn't any previous match.

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.


$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.


Use:

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

You can test it here.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜