Hello!
There is a line like this:

$string = "<body><div></div><div></div><tr><td></td></tr></body>"; 

How to insert a character before the last </div> using preg_replace and regular expressions?
The <tr><td></td></tr> section can be any, so this type of brute force does not fit:

 $string = "<body><div></div><div></div></body>"; function insertInto($what, $object){ $pattern = '/\<\/div\>\<\/body\>$/i'; $replacement = $what.'${0}'; $newString = preg_replace($pattern, $replacement, $object); return $newString; } $string = insertInto('X', $string); print $string; //Результат: <body><div></div><div>X</div></body> 
  • one
    I think at first to deal with your previous question, and then we will deal with it. - Manitikyl
  • Hello! the previous ones have already been sorted out ... - OO
  • and ... litter, did not put a tick. for the previous ATP! - OO

3 answers 3

How to insert a character before the last </div> using preg_replace and regular expressions?

Create a template to search for all characters that end with the </div> and substitute in the replacement string with your character:

 $str = '<body><div></div><div></div><tr><td></td></tr></body>'; echo preg_replace('~<div[^>]*>.+(?=</div>)~s', '$0СИМВОЛ', $str); 

UPD: Corrected pattern. Result:

 <body><div></div><div>СИМВОЛ</div><tr><td></td></tr></body> 
  • The fire ! - OO
  • Can you tell why instead of / do you use ~ ? - OO
  • And ... Everything, I understand. When / you need <>... screen - OO
  • @OO use a tilde ~ because it looks more comfortable, and also because if there are slashes in the template, they do not need to be escaped. - Edward
  • I, a little, reduced ;-) '~^.+(?=</div>)~i' - OO

The function allows only a string search and replace by non-regular patterns:

 $string = '<body><div></div><div></div><tr><td></td></tr></body>'; echo str_replace_end('</div>', 'X', $string); function str_replace_end($search, $replace, $subject) { $pos = strrpos($subject, $search); if($pos !== false) { $subject = substr_replace($subject, $replace . $search, $pos, strlen($search)); } return $subject; } 

At the output we get:

 <body><div></div><div>X</div><tr><td></td></tr></body> 
  • one
    Well, now the second function;) - Manitikyl
  • @Manitikyl, agree)) - Let's say Pie
  • @Manitikyl, it remains only to do by regular expressions) - Let's say Pie
  • I don’t even have any ideas how to implement it on regular basis, so let someone else do it)) - Manitikyl
  • @Manitikyl, it's even easier there, now I'll show you - Let's say Pie
 $string = "<body><div></div><div></div><tr><td></td></tr></body>"; $element = '</div>'; $pos = strripos($string, $element); if ($pos !== FALSE) { $string = substr_replace($string, 'X', $pos, 0); } echo $string;