0

I have this kind of string

$string='Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type <img src="http://www.yourwebite.com/images/assets/livechat-off.png" alt="Our products"/> and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<img src="http://www.yourwebite.com/images/youareon.jpg" alt="Our products"/>the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic';

What i want is to take first img from $string and to get new string like this

$newstring='<img src="http://www.yourwebite.com/images/assets/livechat-off.png" alt="Our products"/>';

That way i can take just one picture from string and display it anywhere, is taht possible?

Tried strip_tags($string, '<img>'); but that way i got all IMG tags, i just want one from string, maybe random, does not to be the first :)

Just made function with help of PeeHaa, txanks mate :)

public function getimagefromstring($string) 

{
 $dom = new DOMDocument();
    // load the string as an HTML document
    $dom->loadHTML($string);

    $xpath = new DOMXPath($dom);

    // match the first image tag found in the document
    $node = $xpath->query('//img[1]');

    // no images found
    if (!$node->length) {
        $image='Hello World';
    }

    else 
    {
    // build the image attributes
    $attrs = '';
    if ($node->item(0)->hasAttributes()) {
        foreach ($node->item(0)->attributes as $attribute) {
            $attrs.= ' ' . $attribute->name . '="' . $attribute->value . '"';
        }
    }
    // display the image
    $image='<img' . $attrs . '>';   
    }

    return $image;   
}
2
  • What have you tried? Do you think you need a regexp or will a simple strpos/substr suffice? Commented Aug 6, 2013 at 9:33
  • Tried strip_tags($string, '<img>'); but that way i got all IMG tags, i just want one from string, maybe random, does not to be the first :) Commented Aug 6, 2013 at 9:35

3 Answers 3

2

This is easy to do with the DOM and XPath classes in PHP:

<?php

function getImage($html)
{
    $dom = new DOMDocument();
    // load the string as an HTML document
    $dom->loadHTML($html);

    $xpath = new DOMXPath($dom);

    // match the first image tag found in the document
    $node = $xpath->query('//img[1]');

    // no images found
    if (!$node->length) {
        return '<img src="myimage">';
    }

    // build the image attributes
    $attrs = '';
    if ($node->item(0)->hasAttributes()) {
        foreach ($node->item(0)->attributes as $attribute) {
            $attrs.= ' ' . $attribute->name . '="' . $attribute->value . '"';
        }
    }

    // display the image
    return '<img' . $attrs . '>';
}

$stringWithImage ='Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type <img src="http://www.yourwebite.com/images/assets/livechat-off.png" alt="Our products"/> and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<img src="http://www.yourwebite.com/images/youareon.jpg" alt="Our products"/>the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic';

$stringWithoutImage = 'Just some random string';

echo getImage($stringWithImage) . "\r\n";
echo getImage($stringWithoutImage) . "\r\n";

Demo: https://eval.in/40828

Sign up to request clarification or add additional context in comments.

4 Comments

This works great, but i have problem, what if string does not have <img> tag then i got error, i want to prevent that :( And if string i dont have <img> i want to use my custom image like <img src="myimage">
Txanks, you are the greatest :)
it is ok, but the problem is i dont know is there <img> tag in string or not?
Have you tried my solution? Because it checks whether there is an image in the string and fallbacks otherwise.
0

You can use preg_match to find tag.

preg_match('/(<img[^>]+>)/i', $str, $matches)

the string contains attributes: $matches[1]

now separate src from other tags

preg_match('/(src="[^"]+")/i', $matches[1], $matches)

the string contains url: $matches[1]

Comments

0

The following function will save your lot of time. Must try it

 function extractor($str,$from,$to)
 {
      $from_pos = strpos($str,$from);
      $from_pos = $from_pos + strlen($from);
      $to_pos   = strpos($str,$to,$from_pos);// to must be after from
      $return   = substr($str,$from_pos,$to_pos-$from_pos);
      unset($str,$from,$to,$from_pos,$to_pos );           
      return $return;

}   

$extracted_str = extractor($string,"<img","/>");

echo "<img" . $extracted_str . "/>";

2 Comments

The above looks very brittle.
I meant brittle like this will break often.

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.