riad
riad

Reputation: 7194

PHP: replace string from a particular string to a particular string

How can I replace a string from a particular string? Please see my example below.

$string_value="<b>Man one</b> <img src=\"http://www.abc.com/image1.jpg\">and <b>Man two</b> <img src=\"http://www.abc.com/img2.png\">";

Now my expected out put is = <b>Man one</b> and <b>man two</b>. only the image tag should be deleted.

So I have to cut the full string from "<img" to ">" from string $string_value. So how can I cut the full string between "<img" to ">" using preg_replace or anything else.

The replacing parameter should be blank space.

Upvotes: 1

Views: 351

Answers (3)

codaddict
codaddict

Reputation: 455380

Looks like you want to strip the tags.
You can do it easily by calling the function strip_tags which gets HTML and PHP tags stripped from a given string.

$string_value = strip_tags($string_value);

EDIT:

Since you want to strip only the <img tag, you can make use of this function:

function strip_only($str, $tags) {
        if(!is_array($tags)) {
                $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
                if(end($tags) == '') array_pop($tags);
        }
        foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
        return $str;
}

and call it as:

$string_value = strip_only($string_value,'img');

Working link

Upvotes: 2

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17305

You can use regular expressions to exclude IMG tags:

<?php
$text = "Man one <img src=\"http://www.abc.com/image1.jpg\">and Man two <img src=\"http://www.abc.com/img2.png\">";
$pattern = "/<img(.*?)>/i";
$replace = '';
print preg_replace($pattern,$replace,$text);
?>

Upvotes: 1

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17305

Just use strip_tags($string_value); and you will get your desired output.

Upvotes: 1

Related Questions