note 105939 modified in function.str-replace by danbrown
| From: | danbrown@php.net | Date: | Tue, 27 Sep 2011 14:25:40 +0000 |
| Subject: | note 105939 modified in function.str-replace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-183491@lists.php.net to get a copy of this message | ||
Note that this does not replace strings that become part of replacement strings. This may be a
problem when you want to remove multiple instances of the same repetative pattern, several times in
a row.
If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f'
resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:
<?php
$challenge = '-aaa----b-c-----d--e---f';
echo str_replace('--', '-', $challenge).'<br>';
echo preg_replace('/--+/', '-', $challenge).'<br>';
?>
This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
--was--
Note that this does not replace strings that become part of replacement strings. This may be a
problem when you want to remove multiple instances of the same repetative pattern, several times in
a row.
If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f'
resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:
$challenge = '-aaa----b-c-----d--e---f';
echo str_replace('--', '-', $challenge).'<br>';
echo preg_replace('/--+/', '-', $challenge).'<br>';
This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
http://php.net/manual/en/function.str-replace.php