-1

I have some HTML content and I would like to replace a tag:

<span class='c1'>MY TEXT</span>

And keep MY TEXT. I tried with:

$result = preg_replace('/(<span class=\'c1\'>)(.*)(<\/span>)/', '$2', $my_string);

But the closed tag still remains? Can you help me and EXPLAIN where is my mistake? I would like to improve myself! Thank you

mck89
  • 18,377
  • 15
  • 87
  • 103
Yoong Kim
  • 300
  • 1
  • 6
  • 13

5 Answers5

2

Try using a lazy match (.*?) instead of a greedy match (.*).

Greedy match means it will match as much as possible before finishing, so if you have another </span> somewhere, it will match that instead. For example:

Using a greedy match:

<span class='c1'>MY TEXT</span><span class='c1'>MY OTHER TEXT</span>
                 ^--greedy match will go from here to here--^

Using a lazy match:

<span class='c1'>MY TEXT</span><span class='c1'>MY OTHER TEXT</span>
                 ^-lazy^                        ^---lazy----^
Jon Newmuis
  • 24,486
  • 2
  • 47
  • 56
0

Try it

$result = preg_replace('/(\<span class=(\'|\")?c1(\'|\")?\>)(.*)(\<\/span\>)/i', '$4', $my_string);
ke20
  • 635
  • 4
  • 19
0

Your match-all group probably consumes too much and you see another </span> from the trailing content. You should try

$result = preg_replace('/(<span class=\'c1\'>)(.*?)(<\/span>)/', '$2', $my_string);

which uses an ungreedy match-all (.*?).

Dio F
  • 2,399
  • 1
  • 20
  • 39
0

Use Simple HTML DOM, it's the best solution for manipulating HTML elements.

Example:

require_once('simple_html_dom.php');
$html = str_get_html('<span class="c1">MY TEXT</span>');
$text = $html->plaintext;

Or if you have an entire HTML document (rather than just a snippet of HTML):

require_once('simple_html_dom.php');
$html = str_get_html('html goes here');
$text = $html->find('span.c1', 0)->plaintext; // Find text from first <span> with the class 'c1'

It's as simple as that.

uınbɐɥs
  • 6,988
  • 5
  • 25
  • 42
0

This will give you perfect result:

preg_match_all('/<span(.*?)class=\'c1\'>(.*?)<\/span>/', '$2', $my_string, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
   echo $result[0][$i];
}
Druid
  • 6,348
  • 3
  • 38
  • 53
Indian
  • 645
  • 7
  • 22