i want change one word from some of the same words with respect to the position of (the first second or third)
example :

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

output :

He SSS had to have had it.

i want
-->: He SSS had to have had it
Or : He had SSS to have had it
Or : He had had to have SSS it

in the case of (my syntax), 'had' is replaced is the first.
if you give me idea, i want syntax should not be reading from the right or left, because it must be ensured where the sequence is replaced from the same word (replace words in a certain order, if I had the same 5 words, then I can easily replace the third word, etc) , what "preg_replace" can do it ? or any idea ?

Dani AI

Generated

Short answer: preg_replace by itself can only stop after N replacements (the fourth parameter), it cannot target "replace only the 3rd match" directly. As suggested that makes plain regex awkward, and was right to point you at preg_replace_callback — that is the clean, reliable way to replace a specific occurrence.

A simple, practical pattern is to count matches in the callback and only return your replacement when the counter equals the desired occurrence. Example:

$text = "one two two two three two";
$pattern = '/\btwo\b/';    // whole-word match
$target = 3;               // 1-based: replace the 3rd match
$replacement = 'XXX';
$counter = 0;

$result = preg_replace_callback($pattern, function($m) use (&$counter, $target, $replacement) {
    $counter++;
    return ($counter === $target) ? $replacement : $m[0];
}, $text);

// $result is "one two two XXX three two"

If you already have token indexes or byte offsets (you said you "gained their positions"), use tokenization or substr_replace instead — tokenizing with preg_split (keep delimiters with PREG_SPLIT_DELIM_CAPTURE) lets you replace the Nth token and rejoin while preserving spacing and punctuation. If you have exact offsets, use substr_replace($string, $replacement, $offset, $length) for an exact, safe swap.

Notes and cautions: use \b and /i or /u as needed to avoid partial or Unicode issues; for very large texts a streaming approach (strpos with offsets or a parser) can be faster than repeated regex. @lasmitch’s idea of working with arrays is valid when you want index-based replacement; otherwise preg_replace_callback is the simplest, most maintainable solution (as discovered).

Recommended Answers

All 6 Replies

There is not a native function in preg_replace for doing something like that, but you should be able to do some nasty regex that would do it. What is the reasoning behind doing such a thing though?

, the reason is a lot of data that needs to be replaced for other data related to a specific position, where i have gained their positions, do you have an idea to solve the case ?

Member Avatar for Member #949455

, the reason is a lot of data that needs to be replaced for other data related to a specific position, where i have gained their positions, do you have an idea to solve the case ?

You need to create something like this:

http://php.about.com/od/advancedphp/ss/php_preg_4.htm

anothers words you need another array or something like this:

$string1 = array ('had','had','to','have','had','it');
$string2 = array ('He','had','had','to','have','had','it');
echo preg_replace('/had/', 'SSS', $string1, 1);

You have to play around with it because it's a regular expression.

@lasmitch : at http://php.about.com/od/advancedphp/ss/php_preg_4.htm we didn't find how get output :
'The' dog likes to sit on 'the' fence. He also likes to climb 'a' tree,
how of the three words ("the") only replace one ?
example :
a dog likes to sit on the fence. He also likes to climb the tree,
The dog likes to sit on a fence. He also likes to climb the tree,
The dog likes to sit on the fence. He also likes to climb a tree

You can control it if you use preg_replace_callback

, thank you, problem has been solved with preg_replace_callback

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.