Der Hund rennt und rennt und läuft und läuft und läuft...
<?php
/**
str_replace_count -- Replace the given number of occurrences
of the search string with the replacement string
string str_replace_count(string search, string replace, string subject, int count)
These functions return a string with some occurrences of search in subject replaced
with the given replace value. The difference to str_replace() from PHP5 is the
interpretation of the count-parameter. In PHP5 it is a reference-parameter and
returns the number on replacements; here it is a value-parameter and gives
the number of maximal replacements. For example, you just want to replace the
first two occurrences, so set this parameter to 2.
Here are two ways of a possible implementation but you should use the first one
Version 1.0 by David Tibbe, 2004/09/01
**/
$durchsuchen = 'Der Hund läuft und läuft und läuft und läuft und läuft...';
$searchen = 'läuft';
$ersetzen = 'rennt';
function str_replace_count($search, $replace, $subject, $count) {
$oft = 0;
$start = 0;
$pos = strpos($subject, $search);
while ($oft < $count && $pos !== FALSE) {
$hlp = substr($subject, 0, $pos);
$hlp .= $replace;
$start = $pos + strlen($search);
$hlp .= substr($subject, $start);
$subject = $hlp;
$oft++;
$pos = strpos($subject, $search, $start);
}
return $subject;
}
function str_replace_count_2($search, $replace, $subject, $count) {
$array = explode($search, $subject);
$subject = '';
for ($i = 0; $i < sizeof($array) - 1; $i++) {
if ($i < $count) {
$subject .= $array[$i].$replace;
} else {
$subject .= $array[$i].$search;
}
}
$subject .= $array[sizeof($array) - 1];
return $subject;
}
echo str_replace_count($searchen, $ersetzen, $durchsuchen, 2);
echo '<hr>';
echo str_replace_count_2($searchen, $ersetzen, $durchsuchen, 2);
echo '<hr>';
highlight_file(__FILE__);
?>