1

this is my string

$var = 'foo<ul class="foo"> test </ul>foo<ul class="bar">foo</ul><ul></ul>foo';

this is my regex

/<ul[^>]*>.*?<\/ul>/g

this is my code

$var = preg_replace('/<ul[^>]*>.*?<\/ul>/', 'bar', $var);

i want to replace all ul elements to bar so after this code my string should look like this

foo barfoo bar barfoo

It works in regex101.com perfectly, but doesn't replace anyting in php Any ideas what's wrong with my code or regex?

//edit
After answers, I tried this and worked then I realized my original string had newlines in it. So I changed my regex to this and it works now

/<ul[^>]*>(.|\r|\n)*?<\/ul>/g

Thanks for your answers :)

morikalina
  • 55
  • 1
  • 5

2 Answers2

0

Well, I had those code tested and it turned out OK:

$var = 'foo<ul class="foo"> test </ul>foo<ul class="bar">foo</ul><ul></ul>foo';
$var = preg_replace('/<ul[^>]*>.*?<\/ul>/', 'bar', $var);
echo $var;

please try it.

yip
  • 123
  • 1
  • 11
  • in addition, the "g" modifier is not supported in PHP; LINK:http://php.net/manual/zh/reference.pcre.pattern.modifiers.php – yip Jan 13 '15 at 14:48
  • This is exactly the same code as he has given. And we established in the comments that his code worked! – Antony D'Andrea Jan 13 '15 at 14:56
-1

To get the result as you mentioned in your question foo barfoo bar barfoo try following

<?php

$var = 'foo<ul class="foo"> test </ul>foo<ul class="bar">foo</ul><ul></ul>foo';
$var = preg_replace('/<ul[^>]*>.*?<\/ul>/', ' bar', $var);
echo $var;

?>

I added a space in replace string ' bar'

Hope this helps.

karmendra
  • 2,206
  • 8
  • 31
  • 49
  • I do not understand, what was the point of this question, and do not understand a -1 on my answer which exactly addressed the question asked. Ridiculous indeed. – karmendra Jan 14 '15 at 08:37