0

我想:他有 XXX 有过。或者:他必须要XXX才行。

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

输出 :

他XXX必须拥有它。

在这种情况下,'had'被替换为第一个。

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

4

4 回答 4

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

于 2013-04-24T11:56:26.040 回答
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
);
于 2013-04-24T12:01:00.960 回答
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.
)

我管理这段代码尝试优化它。

于 2013-04-24T12:08:04.037 回答
0

可能不会因此赢得任何优雅,但很短:

$string = "He had had to have had it.";
echo strrev(preg_replace('/dah/', 'XXX', strrev($string), 1));
于 2013-04-24T12:08:19.843 回答