0

私が欲しい:彼はそれを持っていたXXXを持っていました。または : 彼はそれを XXX 持っていなければなりませんでした。

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

出力:

彼はそれを持っていたに違いありません。

の場合は、'had' が最初に置き換えられます。

2番目と3番目を使いたいです。右または左から読み取らない場合、「preg_replace」でできることは何ですか?

4

4 に答える 4

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 に答える