preg_replace - 替换某些字符

时间:2013-04-24 11:49:57

标签: php preg-replace

我想:他有XXX得到它。或者:他必须拥有XXX。

$string = "He had had to have had it.";
echo preg_replace('/had/', 'XXX', $string, 1);

输出:

  

他XXX必须拥有它。

在案例中,'have'被替换为第一个。

我想使用第二个和第三个。不是从右边或左边读,“preg_replace”可以做什么?

4 个答案:

答案 0 :(得分:2)

试试这个:

  <?php
function my_replace($srch, $replace, $subject, $skip=1){
    $subject = explode($srch, $subject.' ', $skip+1);
    $subject[$skip] = str_replace($srch, $replace, $subject[$skip]);
    while (($tmp = array_pop($subject)) == '');
    $subject[]=$tmp;
    return implode($srch, $subject);
}
$test ="He had had to have had it.";;
echo my_replace('had', 'xxx', $test);
echo "<br />\n";
echo my_replace('had', 'xxx', $test, 2);
?>

查看CodeFiddle

答案 1 :(得分:2)

$string = "He had had to have had it.";
$replace = 'XXX';
$counter = 0;  // Initialise counter
$entry = 2;    // The "found" occurrence to replace (starting from 1)

echo preg_replace_callback(
    '/had/',
    function ($matches) use ($replace, &$counter, $entry) {
        return (++$counter == $entry) ? $replace : $matches[0];
    },
    $string
);

答案 2 :(得分:0)

试试这个

的解决方案

function generate_patterns($string, $find, $replace) {

// Make single statement
// Replace whitespace characters with a single space
$string = preg_replace('/\s+/', ' ', $string);

// Count no of patterns
$count = substr_count($string, $find);

// Array of result patterns
$solutionArray = array();

// Require for substr_replace
$findLength = strlen($find);

// Hold index for next replacement
$lastIndex = -1;

  // Generate all patterns
  for ( $i = 0; $i < $count ; $i++ ) {

    // Find next word index
    $lastIndex = strpos($string, $find, $lastIndex+1);

    array_push( $solutionArray , substr_replace($string, $replace, $lastIndex, $findLength));
  }

return $solutionArray;
}

$string = "He had had to have had it.";

$find = "had";
$replace = "yz";

$solutionArray = generate_patterns($string, $find, $replace);

print_r ($solutionArray);

输出

Array
(
    [0] => He yz had to have had it.
    [1] => He had yz to have had it.
    [2] => He had had to have yz it.
)

我管理此代码尝试优化它。

答案 3 :(得分:0)

可能不会用这个赢得任何优雅,但很短:

$string = "He had had to have had it.";
echo strrev(preg_replace('/dah/', 'XXX', strrev($string), 1));