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 ?

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?

@pixelsoul, 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 LastMitch

@pixelsoul, 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

@pritaeas, 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.