0

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 ?

4
Contributors
6
Replies
34
Views
4 Years
Discussion Span
Last Post by ivanichi
1

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?

0

@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 ?

0

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

Edited by LastMitch: grammer

0

@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

1

@pritaeas, thank you, problem has been solved with preg_replace_callback

Edited by ivanichi

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.