0

Hi I would like to remove a img tag with it's src is a url in a content using preg_replace

ex.

    $content = "<center><img src="http://example.net/wp-content/uploads/2012/10/cell-degeneration-contn.jpg" alt="" title="cell-degeneration-contn" width="950" height="272" class="alignnone size-full wp-image-100" /></center><h2>A first-in-class approach to stop & reverse </h2>";

so output would be:

    $content="<center></center><h2>A first-in-class approach to stop & reverse </h2>";

but best output would be if possible is :

    $content="A first-in-class approach to stop & reverse ";
2
  • Does it have to use preg_replace? Commented Nov 2, 2012 at 17:26
  • 1
    welcome to stack overflow. As Marc B pointed it seems that regex is not the way to operate html text; just clarify if you really to use need preg_replace Commented Nov 2, 2012 at 17:49

2 Answers 2

2

preg_match_all() would work here, but with HTML it's not the most efficient.

$content = '<center><img src="http://example.net/wp-content/uploads/2012/10/cell-degeneration-contn.jpg" alt="" title="cell-degeneration-contn" width="950" height="272" class="alignnone size-full wp-image-100" /></center><h2>A first-in-class approach to stop & reverse </h2>';

preg_match("/<h2>(.*)<\/h2>/",$content,$matches);
$output = $matches[1];
echo $output;

The easiest way is to just use strip_tags()

$output = strip_tags($content);
echo $output;
Sign up to request clarification or add additional context in comments.

1 Comment

why preg_match_all and not preg_match ? :-??
1

You can do that this way:

    $content = "<center><img src='http://example.net/wp-content/uploads/2012/10/cell-degeneration-contn.jpg' alt='' title='cell-degeneration-contn' width='950' height='272' class='alignnone size-full wp-image-100' /></center><h2>A first-in-class approach to stop & reverse </h2>'";
    preg_match("/<h2>(.+)<\/h2>/", $content, $matches);  
    $match = $matches[1];
    echo $match;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.