ivanichi
ivanichi

Reputation: 49

preg_replace - replace certain character

i want : He had XXX to have had it. Or : He had had to have XXX it.

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

output :

He XXX had to have had it.

in the case of, 'had' is replaced is the first.

I want to use the second and third. not reading from the right or left, what "preg_replace" can do it ?

Upvotes: 0

Views: 941

Answers (4)

Navnath Godse
Navnath Godse

Reputation: 2225

Try this

Solution

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);

Output :

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.
)

I manage this code try to optimize it.

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

$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
);

Upvotes: 2

fvu
fvu

Reputation: 32953

Probably not going to win any concours d'elegance with this, but very short:

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

Upvotes: 0

Vijaya Pandey
Vijaya Pandey

Reputation: 4282

Try this:

  <?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);
?>

Look at CodeFiddle

Upvotes: 2

Related Questions