Deleting img tag from string - php

I've got a string, $content, that contains:
<p>Some random text <img class="alignnone" src="logo.png" alt="" width="1920" height="648"></p>
Now I want to delete the image tag:
<img class="alignnone" src="logo.png" alt="" width="1920" height="648">
I tried strip_tags but that isn't working anymore.
$content = strip_tags($content, '<img></img>');

Here is a complete working example.
<?php
$content = "<p>Some random text <img class=\"alignnone\" src=\"logo.png\" alt=\"\" width=\"1920\" height=\"648\"></p>";
echo strip_tags($content,"<p>");
?>

If <p></p> is the only other tag you'll have you can use strip_tags like this:
$content = strip_tags($content, '<p></p>');
If there may be other tags you want to keep, just add them to the second argument of strip_tags
You can also use a combination of string functions to achieve this:
$count = substr_count($c, '<img ');
while($count >= 1){
$i = strpos($c, '<img ');
$j = strpos($c, '>',$i)+1;
$c = substr($c, 0,$i) . substr($c,$j);
$count--;
}
echo $c;
This also takes care of multiple <img> tags

You could search for the img-Tags with the strpos()-function:
http://www.w3schools.com/php/func_string_strpos.asp
Once you know the start- and ending-position inside the string you can access the parts you need with the substr()-function:
http://php.net/manual/de/function.substr.php
In your example:
$left = strpos($content,'<img');
//$left should now be "20"
//to find the closing >-tag you need the string starting from <img... so you assign that to $rest:
$rest = substr($content,(strlen($content)-$left+1)*(-1));
$right = strpos($rest,">")+$left;
//now you know where the img ends so you can get the string surrounding it with:
$surr = substr($content,0,$left).substr($content,(strlen($content)-$right)*(-1));
Edit: Tested, will work for deleting the first img-Tag

Related

Regex replace keyword with different string by loop (PHP)

Let say I have a string
$content = "hello . wow . cool . yes!";
It's easy to just replace the dot to another string:
echo preg_replace("/\./", "<img>", $content);
so the output is:
hello <img> wow <img> cool <img> yes!
however, is there any way to replace it one by one?
for example, I have an array and would like to insert them into the string.
$arr = ['<img src="a"/>', '<img src="b"/>', '<img src="c"/>'];
the expected output:
hello <img src="a"/> wow <img src="b"/> cool <img src="c"/> yes!
I can use preg_match_all to get the separator but still have no idea how to replace it respectively.
Thank you for any help.
Use preg_replace_callback. Store the number of the current full stop in a static variable. Access $arr from the callback with use (). Use modulo in case there are not enough items in $arr.
<?php
$content = 'hello . wow . cool . yes!';
$arr = ['<img src="a"/>', '<img src="b"/>', '<img src="c"/>'];
$content = preg_replace_callback ('/\./', function ($_) use ($arr) {
static $count = 0;
return $arr [$count++ % count ($arr)];
}, $content);
echo ($content);
http://sandbox.onlinephpfunctions.com/code/f9115bdb6eb17e30012d987ed1fc4b95e7c10d33.

How to get first image in string using php?

I use this code:
<?php
$texthtml = '<p>test</p><br><p><img src="1.jpeg" alt=""><br></p><p><img src="2.png" alt=""><br><img src="3.png" alt=""></p>';
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
echo $image['src'];
?>
However, when I test it, I get last image (3.png) from a string.
I want to know how can I do for get first image (1.jpeg) in a string.
Try:
preg_match('/<img(?: [^<>]*?)?src=([\'"])(.*?)\1/', $texthtml, $image);
echo isset($image[1]) ? $image[1] : 'default.png';
Regex is not suitable for html tags.
You can read about it here: RegEx match open tags except XHTML self-contained tags
I suggest DOM document if it's more complex than what you have shown here.
If it's not more complex than this I suggest strpos to find the words and "trim" it with substr.
$texthtml = '<p>test</p><br><p><img src="1.jpeg" alt=""><br></p><p><img src="2.png" alt=""><br><img src="3.png" alt=""></p>';
$search = 'img src="';
$pos = strpos($texthtml, $search)+ strlen($search); // find postition of img src" and add lenght of img src"
$lenght= strpos($texthtml, '"', $pos)-$pos; // find ending " and subtract $pos to find image lenght.
echo substr($texthtml, $pos, $lenght); // 1.jpeg
https://3v4l.org/48iiI

Change links in text to links without changing html tags

I have written some code that change text links to links but it also changes the src attribute of my img tags to link like
<img src="some url"/><br>
http://google.com<br>
http://beezfeed.cu.ma<br>
Here my code change it to
<img src="some url"/><br>
http://google.com<br>
http://beezfeed.cu.ma<br>
I want it to leave img tag and do that thing with only text. Here is my code
function make_links_clickable($text){
return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#? &;//=]+)!i', '$1', $text);
}
Try explode() then strip html tags to avoid img tag
$str = '<img src="some url"/><br>
http://google.com<br>
http://beezfeed.cu.ma<br>';
$arr = explode('<br>', $str);
foreach($arr as $a){
if(!empty($a)){
$a = strip_tags($a);
echo ''.$a.'';
}
}

Replace All HTML img tags with text inside their ALT

for example:
INPUT:
<img "img1.gif" alt="Donkey"><BR>
<img "img2.gif" alt="Horse"><BR>
<img "img3.gif" alt="Orangutan"><BR>
OUTPUT
Donkey
Horse
Orangutan
looked around for this but no cigar. Any ideas? thnx!
for a quick solution use preg_replace()
$text = '<img img1.gif" alt="Donkey"><BR>
<img img2.gif" alt="Horse"><BR>
<img img3.gif" alt="Orangutan"><BR>';
$replace = preg_replace('/<img(.*)alt="(.*)"\>/', "$2", $text);
echo $replace;
Feeling generous today, here's da c0dez:
$html =<<<EOS
<img "img1.gif" alt="Donkey"><BR>
<img "img2.gif" alt="Horse"><BR>
<img "img3.gif" alt="Orangutan"><BR>
EOS;
$d = new DOMDocument;
$d->loadHTML($html);
foreach ($d->getElementsByTagName('img') as $img) {
echo $img->getAttribute('alt'), "\n";
}
You can't have looked around a lot - look at this quite similar question:
How to extract img src, title and alt from html using php?

How to remove first image from string

I have the results from a database that contains images and text. I would like to remove the first image.
Example:
$string = 'This is some text and images
<img src="http://linktoimage" border="0">,
more text and <img src="http://linktoanotherimage"> and so on';
I would like to remove the first image, it is not always the same url.
Thanks for any help.
$string = 'This is some text and images
<img src="http://linktoimage" border="0">,
more text and <img src="http://linktoanotherimage"> and so on';
print preg_replace('/<img(.*)>/i','',$string,1);
The above should return
This is some text and images
,
more text and <img src="http://linktoanotherimage"> and so on
Assuming you know it'll be prefixed by spaces and a line break, and suffixed by a comma and line break (and you want to remove these, too), you can do
print preg_replace("/\n <img(.*)>\,\n /i",'',$string,1);
Which will give you
This is some text and images more text and <img src="http://linktoanotherimage"> and so on
There was a great answer on another Thread
function get_first_image($html){
require_once('SimpleHTML.class.php')
$post_dom = str_get_dom($html);
$first_img = $post_dom->find('img', 0);
if($first_img !== null) {
return $first_img->src;
}
return null;
}
You can do it via Regex expressions however regex isn't really suited for this.
$var = 'This is some text and images
<img src="http://linktoimage" border="0">,
more text and <img src="http://linktoanotherimage"> and so on';
echo preg_replace('/<img.*?>/', '123', $var, 1);
This should do it. ? in the regex is to make it ungreedy.
Being a RegEx newbie, I tend to avoid it and use something like:
$i = strpos($string,'<img');
if ($i !== false) {
$j = strpos($string, '>', $i);
if ($j !== false) $string = substr($string,0,$i) . substr($string,$j);
}
Probably should be $i-1 and/or $j+1 - I never remember exactly what it should be.
Finally nailed it down:
preg_replace('/<img[\S\s]*?>/i','',$txt,1)
This one also works for cases when you might have:
$string = 'This is some text and images
<img
src="http://linktoimage" border="0">,
more text and <img src="http://linktoanotherimage"> and so on';
(a new line character in the tag.)
This code works for me
$html is your html content variable from which you want to remove first image tag.
$str = preg_replace('/(<img[^>]+>)/i','',$html,1);

Categories