1

I have the following string in PHP:

 $string = "<img src=\"url\" >HELLO WORLD<ol>I must replace the text after img and before ol.</ol>";
 print htmlentities($string);

I want to find the substring HELLO WORLD (or whatever substring is, that is just an example of a text that will be completely dynamical), using the delimiters : "<img ... >" and "<ol>" and add <h3> delimiters. So the string above would result in:

 <img src="url" ><h3>HELLO WORLD</h3><ol>I must replace the text after img and before ol.</ol>

I have tried the following code, of course with no success:

 $string = preg_replace("/\<img (.*?)\> (.*?)\<ol\>/", "<img  (.*?)><h3> (.*?)</h3></ol>", $string);

I know how to make very easy substituions, but the above condition is very far from my understanding.

Cesar
  • 514
  • 1
  • 5
  • 16
  • You could use strpos, find the position of HELLO WORLD in the string, place at position + length of HELLO WORLD and after that place

    at the found position. strpos http://php.net/manual/en/function.strpos.php

    – namlik Sep 07 '16 at 06:17
  • @namlik This doesn't answer the question as the OP has clearly mentioned that OP wants to search HELLO WORD between "" and "" tags only. – Indrajit Sep 07 '16 at 06:19
  • @namlik is right. I must stress that I don't know that I will find HELLO WORLD, it could be any string. This is why I am using regular expressions. Strpos is not valid as I should know that I am going to find "HELLO WORLD". – Cesar Sep 07 '16 at 06:23
  • It is more specific, in fact the question would be the use of backreferences, in the form of variables $n, with n = 1,...,99. – Cesar Sep 07 '16 at 08:15
  • @Indrajit take a look at the post before the edit, you'll see that the part about (wathever substring it is) has been added later. – namlik Sep 09 '16 at 14:00

1 Answers1

1

I have found the answer by trial-and-error:

 $string = "<img src=\"url\" >HELLO WORLD<ol>I must find the text after img and before ol.</ol>";

 $string2 = preg_replace("/<img (.*?)>(.*?)<ol>/", "<img $1><h3>$2</h3><ol>", $string);
 print htmlentities($string) . " <br />" . htmlentities($string2);

Explanation: I add the delimiters, and use $1 and $2 for matching the results between the delimiters in the right order.

Cesar
  • 514
  • 1
  • 5
  • 16