I have an HTML with a number of images inside it. Suppose I have one url which is of one of the images inside the HTML content. What if I have to replace the image inside HTML with some custom text in PHP?
<div>
<p>Some text<img src="a.jpg" class="testclass" alt="image" title="image"/></p>
<p>Some more text<img src="b.jpg" class="testclass2" alt="image2" title="image2"/></p>
</div>
And suppose I have to replace <img src="a.jpg" class="testclass" alt="image" title="image"/> with some custom text but the only information I have is the image URL i.e "a.jpg". How to do it in PHP?
Using regular expressions for this is not the ideal solution. Such expressions can become very complicated to deal with quotes, white space, attribute order, scripts,... etc in HTML.
The preferred method is to use a DOM parser, which PHP offers out-of-the-box.
Here is some code you could use to get what you want:
// main function: pass it the DOM, image URL and replacement text
function DOMreplaceImagesByText($dom, $img_src, $text) {
foreach($dom->getElementsByTagName('img') as $img) {
if ($img->getAttribute("src") == "a.jpg") {
$span = $dom->createElement("span", $text);
$img->parentNode->replaceChild($span, $img);
};
}
}
// utility function to get innerHTML of an element
function DOMinnerHTML($element) {
$innerHTML = "";
foreach ($element->childNodes as $child) {
$innerHTML .= $element->ownerDocument->saveHTML($child);
}
return $innerHTML;
}
// test data
$html = '<div>
<p>Some text<img src="a.jpg" class="testclass" alt="image" title="image"/></p>
<p>Some more text<img src="b.jpg" class="testclass2" alt="image2" title="image2"/></p>
</div>';
// create DOM for given HTML
$dom = new DOMDocument();
$dom->loadHTML($html);
// call our function to make the replacement(s)
DOMreplaceImagesByText($dom, "a.jpg", "custom text");
// convert back to HTML
$html = DOMinnerHTML($dom->getElementsByTagName('body')->item(0));
// show result (for demo only, in reality you would not use htmlentities)
echo htmlentities($html);
The above code will output:
<div>
<p>Some text<span>custom text</span></p>
<p>Some more text<img src="b.jpg" class="testclass2" alt="image2" title="image2"></p>
</div>
Regular Expression
As stated above, regular expressions are not well-suited for this job, but I will provide you one just for completeness sake:
function HTMLreplaceImagesByText($html, $img_src, $text) {
// escape special characters in $img_src so they work as
// literals in the main regular expression
$img_src = preg_replace("/(\W)/", "\\\\$1", $img_src);
// main regular expression:
return preg_replace("/<img[^>]*?\ssrc\s*=\s*[\'\"]" . $img_src
. "[\'\"].*?>/si", "<span>$text</span>", $html);
}
$html = '<div>
<p>Some text<img src="a.jpg" class="testclass" alt="image" title="image"/></p>
<p>Some more text<img src="b.jpg" class="testclass2" alt="image2" title="image2"/></p>
</div>';
$html = HTMLreplaceImagesByText($html, "a.jpg", "custom text");
echo htmlentities($html);
The output will be the same as with the DOM parsing solution. But it will fail in many specific situations, where the DOM solution will not have any problem. For instance, if a matching image tag appears in a comment or as a string within a script tag, it will make the replacement, while it shouldn't. Worse, when the matching image tag has a greater-than sign in an attribute value, the replacement will produce wrong results.
There are many other instances where it will go wrong.
Related
I am using Nette PHP (framework shouldn't matter), and I'm trying to replace parts of html with different one - if image tag has class=, it will be replaced with class="image-responsive, and if not it will get a new attribute class="image-responsive".
I'm getting that HTML as a string, which will be saved in database!
This is my current code. It can find the strings, but what I need help with is replacing parts of the html.
public static function ImageAddClass($string)
{
// Match Img with class="$1 (group 1 here)"
$regex_img = '/(<img)([^>]*[^>]*)(\/>)/mi';
$regex_imgClass = '/(<img[^>]* )(class=\")([^\"]*\"[^>]*>)/mi';
$html = $string;
if (preg_match_all($regex_img, $html, $matches)) {
for ($x = 0; $x < count($matches[0]); $x++) {
bdump($matches[0]);
bdump($matches[0][$x]);
bdump($x);
if (preg_match($regex_imgClass, $matches[0][$x])) {
$html = preg_replace($regex_imgClass, '$1class="image-responsiveO $3', $html);
} else if (preg_match($regex_img, $matches[0][$x])) {
$html = preg_replace($regex_img, '$1 class="image-responsiveN" $2$3', $html);
}
}
return $html;
}
}
Covering all scenarios where an img tag might have no class attribute, an orphaned class attribute, a blank class attribute, a class attribute with one or more other words, and a class attribute that already contains image-responsive -- I prefer to use XPath to filter the elements.
Not only is parsing HTML with a legitimate DOM parser like DOMDocument more robust/reliable than regex, the accompanying XPath syntax is highly intuitive.
Pay close attention to how the XPath query pads the haystack class and the needle class with spaces as a means to ensure whole word matching.
Any images that are iterated will have the desired value added to the element's class attribute.
Code: (Demo)
$html = <<<HTML
<div>
<img src="">
<img src="" class>
<img src="" class="image-responsive">
<img src="" class="">
<img src="image-responsive" class="classy">
<img src="" class="image-responsiveness">
<span class='NOT-responsive'></span>
<img src="" class = "foo image-responsive">
</div>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//img[not(contains(concat(" ", #class, " ")," image-responsive "))]') as $img) {
$img->setAttribute('class', ltrim($img->getAttribute('class') . ' image-responsive'));
}
echo $dom->saveHTML();
Output:
<div>
<img src="" class="image-responsive">
<img src="" class="image-responsive">
<img src="" class="image-responsive">
<img src="" class="image-responsive">
<img src="image-responsive" class="classy image-responsive">
<img src="" class="image-responsiveness image-responsive">
<span class="NOT-responsive"></span>
<img src="" class="foo image-responsive">
</div>
Related content:
Replace empty alt in wordpress post content with filter
Xpath syntax for "and not contains"
Parsing HTML with PHP To Add Class Names
How can I match on an attribute that contains a certain string?
As a slight variation, you can access all img tags without XPath, then use preg_match() calls to determine which tags should receive the new class. The word boundary character \b is not useful in this case because class names may contain non-word characters.
Code: (Demo)
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($dom->getElementsByTagName('img') as $img) {
$class = $img->getAttribute('class');
if (!preg_match('/(?:^| )image-responsive(?: |$)/', $class)) {
$img->setAttribute('class', ltrim("$class image-responsive"));
}
}
echo $dom->saveHTML();
// same output as first snippet
I am reading a html content. There are image tags such as
<img onclick="document.location='http://abc.com'" src="http://a.com/e.jpg" onload="javascript:if(this.width>250) this.width=250">
or
<img src="http://a.com/e.jpg" onclick="document.location='http://abc.com'" onload="javascript:if(this.width>250) this.width=250" />
I tried to reformat this tags to become
<img src="http://a.com/e.jpg" />
However i am not successful. The codes i tried to build so far is like
$image=preg_replace('/<img(.*?)(\/)?>/','',$image);
anyone can help?
Here's a version using DOMDocument that removes all attributes from <img> tags except for the src attribute. Note that doing a loadHTML and saveHTML with DOMDocument can alter other html as well, especially if that html is malformed. So be careful - test and see if the results are acceptable.
<?php
$html = <<<ENDHTML
<!doctype html>
<html><body>
<img onclick="..." src="http://a.com/e.jpg" onload="...">
<div><p>
<img src="http://a.com/e.jpg" onclick="..." onload="..." />
</p></div>
</body></html>
ENDHTML;
$dom = new DOMDocument;
if (!$dom->loadHTML($html)) {
throw new Exception('could not load html');
}
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//img') as $img) {
// unfortunately, cannot removeAttribute() directly inside
// the loop, as this breaks the attributes iterator.
$remove = array();
foreach ($img->attributes as $attr) {
if (strcasecmp($attr->name, 'src') != 0) {
$remove[] = $attr->name;
}
}
foreach ($remove as $attr) {
$img->removeAttribute($attr);
}
}
echo $dom->saveHTML();
Match one at a time then concat string, I am unsure which language you are using so ill explain in pseudo:
1.Find <img with regex place match in a string variable
2.Find src="..." with src=".*?" place match in a string variable
3.Find the end /> with \/> place match in a string variable
4.Concat the variables together
Let's say I've have the code like this:
<img src="001">
<img src="002">
<p>Some content here.</p>
<img src="003">
What I want to do now is to match the first two images (001 and 002) and store that part of the code in variable. I don't want to do anything with third image.
Id used something like preg_match_all('/<img .*>/', $result); but it obviously matched all the images. Not just those which appear on the top of the code. How to modify that regular expression to select just images that are on top of the code.
What I want to do is to now. I've have <h2> tag with title in one variable and the code above in the second. I want to move the first X images before the <h2> tag OR insert that <h2> tag after first X images. All that in back-end PHP. Would be fun to make it with CSS, but flexbox is not yet here.
You need to divide the problem to solve it. You have got two main parts here:
Division of the HTML into Top and Bottom parts.
Doing the DOMDocument manipulation on (both?) HTML strings.
Let's just do that:
The first part is actually quite simple. Let's say all line separators are "\n" and the empty line is actually an empty line "\n\n". Then this is a simple string operation:
list($top, $bottom) = explode("\n\n", $html, 2);
This solves the first part already. Top html is in $top and the rest we actually do not need to care much about is stored into $bottom.
Let's go on with the second part.
With simple DOMDocument operations you can now for example get a list of all images:
$topDoc = new DOMDocument();
$topDoc->loadHTML($top);
$topImages = $topDoc->getElementsByTagname('img');
The only thing you need to do now is to remove each image from it's parent:
$image->parentNode->removeChild($image);
And then insert it before the <h2> element:
$anchor = $topDoc->getElementsByTagName('h2')->item(0);
$anchor->parentNode->insertBefore($image, $anchor);
And you're fine. Full code example:
$html = <<<HTML
<h2>Title here</h2>
<img src="001">
<p>Some content here. (for testing purposes)</p>
<img src="002">
<h2>Second Title here (for testing purposes)</h2>
<p>Some content here.</p>
<img src="003">
HTML;
list($top, $bottom) = explode("\n\n", $html, 2);
$topDoc = new DOMDocument();
$topDoc->loadHTML($top);
$topImages = $topDoc->getElementsByTagname('img');
$anchor = $topDoc->getElementsByTagName('h2')->item(0);
foreach($topImages as $image) {
$image->parentNode->removeChild($image);
$anchor->parentNode->insertBefore($image, $anchor);
}
foreach($topDoc->getElementsByTagName('body')->item(0)->childNodes as $child)
echo $topDoc->saveHTML($child);
echo $bottom;
Output:
<img src="001"><img src="002"><h2>Title here</h2>
<p>Some content here. (for testing purposes)</p>
<h2>Second Title here (for testing purposes)</h2>
<p>Some content here.</p>
<img src="003">
I have :
Title
And :
Title
I want to replace link to text "Title", but only from http://abc.com. But I don't know how ( I tried Google ), can you explain for me. I'm not good in PHP.
Thanks in advance.
Not sure I really understand what you're asking, but if you :
Have a string that contains some HTML
and want to replace all links to abc.com by some text
Then, a good solution (better than regular expressions, should I say !) would be to use the DOM-related classes -- especially, you can take a look at the DOMDocument class, and its loadHTML method.
For example, considering that the HTML portion is declared in a variable :
$html = <<<HTML
<p>some text</p>
Title
<p>some more text</p>
Title
<p>and some again</p>
HTML;
You could then use something like this :
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags = $dom->getElementsByTagName('a');
for ($i = $tags->length - 1 ; $i > -1 ; $i--) {
$tag = $tags->item($i);
if ($tag->getAttribute('href') == 'http://abc.com') {
$replacement = $dom->createTextNode($tag->nodeValue);
$tag->parentNode->replaceChild($replacement, $tag);
}
}
echo $dom->saveHTML();
And this would get you the following portion of HTML, as output :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>some text</p>
Title
<p>some more text</p>
Title
<p>and some again</p>
</body></html>
Note that the whole Title portion has been replaced by the text it contained.
If you want some other text instead, just use it where I used $tag->nodeValue, which is the current content of the node that's being removed.
Unfortunately, yes, this generates a full HTML document, including the doctype declaration, <html> and <body> tags, ...
To cover another interpreted case:
$string = 'Title Title';
$pattern = '/\<\s?a\shref[\s="\']+([^\'"]+)["\']\>([^\<]+)[^\>]+\>/';
$result = preg_replace_callback($pattern, 'replaceLinkValueSelectively', $string);
function replaceLinkValueSelectively($matches)
{
list($link, $URL, $value) = $matches;
switch ($URL)
{
case 'http://abc.com':
$newValue = 'New Title';
break;
default:
return $link;
}
return str_replace($value, $newValue, $link);
}
echo $result;
input
Title Title
becomes
New Title Title
$string is your input, $result is your input modified. You can define more URLs as cases.
Please note: I wrote that regular expression hastily, and I'm quite the novice. Please check that it suits all your intended cases.
I would like to know how this can be achieved.
Assume: That there's a lot of html code containing tables, divs, images, etc.
Problem: How can I get matches of all occurances. More over, to be specific, how can I get the img tag source (src = ?).
example:
<img src="http://example.com/g.jpg" alt="" />
How can I print out http://example.com/g.jpg in this case. I want to assume that there are also other tags in the html code as i mentioned, and possibly more than one image. Would it be possible to have an array of all images sources in html code?
I know this can be achieved way or another with regular expressions, but I can't get the hang of it.
Any help is greatly appreciated.
While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.
What I recommend you do is use a DOM parser such as SimpleHTML and use it as such:
function get_first_image($html) {
require_once('SimpleHTML.class.php')
$post_html = str_get_html($html);
$first_img = $post_html->find('img', 0);
if($first_img !== null) {
return $first_img->src;
}
return null;
}
Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute.
A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the alt attribute to be after the src or the opposite, and to overcome this limitation would add more complexity to the regular expression.
Also, consider the following. To properly match an <img> tag using regular expressions and to get only the src attribute (captured in group 2), you need the following regular expression:
<\s*?img\s+[^>]*?\s*src\s*=\s*(["'])((\\?+.)*?)\1[^>]*?>
And then again, the above can fail if:
The attribute or tag name is in capital and the i modifier is not used.
Quotes are not used around the src attribute.
Another attribute then src uses the > character somewhere in their value.
Some other reason I have not foreseen.
So again, simply don't use regular expressions to parse a dom document.
EDIT: If you want all the images:
function get_images($html){
require_once('SimpleHTML.class.php')
$post_dom = str_get_dom($html);
$img_tags = $post_dom->find('img');
$images = array();
foreach($img_tags as $image) {
$images[] = $image->src;
}
return $images;
}
Use this, is more effective:
preg_match_all('/<img [^>]*src=["|\']([^"|\']+)/i', $html, $matches);
foreach ($matches[1] as $key=>$value) {
echo $value."<br>";
}
Example:
$html = '
<ul>
<li><a target="_new" href="http://www.manfromuranus.com">Man from Uranus</a></li>
<li><a target="_new" href="http://www.thevichygovernment.com/">The Vichy Government</a></li>
<li><a target="_new" href="http://www.cambridgepoetry.org/">Cambridge Poetry</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value1.jpg" />
<li>Electronaut Records</li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value2.jpg" />
<li><a target="_new" href="http://www.catseye-crew.com">Catseye Productions</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value3.jpg" />
</ul>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="res/upload.jpg" />
<li><a target="_new" href="http://www.manfromuranus.com">Man from Uranus</a></li>
<li><a target="_new" href="http://www.thevichygovernment.com/">The Vichy Government</a></li>
<li><a target="_new" href="http://www.cambridgepoetry.org/">Cambridge Poetry</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value4.jpg" />
<li>Electronaut Records</li>
<img src="value5.jpg" />
<li><a target="_new" href="http://www.catseye-crew.com">Catseye Productions</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value6.jpg" />
';
preg_match_all('/<img .*src=["|\']([^"|\']+)/i', $html, $matches);
foreach ($matches[1] as $key=>$value) {
echo $value."<br>";
}
Output:
value1.jpg
value2.jpg
value3.jpg
res/upload.jpg
value4.jpg
value5.jpg
value6.jpg
This works for me:
preg_match('#<img.+src="(.*)".*>#Uims', $html, $matches);
$src = $matches[1];
i assume all your src= have " around the url
<img[^>]+src=\"([^\"]+)\"
the other answers posted here make other assumsions about your code
I agree with Andrew Moore. Using the DOM is much, much better. The HTML DOM images collection will return to you a reference to all image objects.
Let's say in your header you have,
<script type="text/javascript">
function getFirstImageSource()
{
var img = document.images[0].src;
return img;
}
</script>
and then in your body you have,
<script type="text/javascript">
alert(getFirstImageSource());
</script>
This will return the 1st image source. You can also loop through them along the lines of, (in head section)
function getAllImageSources()
{
var returnString = "";
for (var i = 0; i < document.images.length; i++)
{
returnString += document.images[i].src + "\n"
}
return returnString;
}
(in body)
<script type="text/javascript">
alert(getAllImageSources());
</script>
If you're using JavaScript to do this, remember that you can't run your function looping through the images collection in your header. In other words, you can't do something like this,
<script type="text/javascript">
function getFirstImageSource()
{
var img = document.images[0].src;
return img;
}
window.onload = getFirstImageSource; //bad function
</script>
because this won't work. The images haven't loaded when the header is executed and thus you'll get a null result.
Hopefully this can help in some way. If possible, I'd make use of the DOM. You'll find that a good deal of your work is already done for you.
I don't know if you MUST use regex to get your results. If not, you could try out simpleXML and XPath, which would be much more reliable for your goal:
First, import the HTML into a DOM Document Object. If you get errors, turn errors off for this part and be sure to turn them back on afterward:
$dom = new DOMDocument();
$dom -> loadHTMLFile("filename.html");
Next, import the DOM into a simpleXML object, like so:
$xml = simplexml_import_dom($dom);
Now you can use a few methods to get all of your image elements (and their attributes) into an array. XPath is the one I prefer, because I've had better luck with traversing the DOM with it:
$images = $xml -> xpath('//img/#src');
This variable now can treated like an array of your image URLs:
foreach($images as $image) {
echo '<img src="$image" /><br />
';
}
Presto, all of your images, none of the fat.
Here's the non-annotated version of the above:
$dom = new DOMDocument();
$dom -> loadHTMLFile("filename.html");
$xml = simplexml_import_dom($dom);
$images = $xml -> xpath('//img/#src');
foreach($images as $image) {
echo '<img src="$image" /><br />
';
}
I really think you can not predict all the cases with on regular expression.
The best way is to use the DOM with the PHP5 class DOMDocument and xpath. It's the cleanest way to do what you want.
$dom = new DOMDocument();
$dom->loadHTML( $htmlContent );
$xml = simplexml_import_dom($dom);
$images = $xml -> xpath('//img/#src');
You can try this:
preg_match_all("/<img\s+src=\"(.+)\"/i", $html, $matches);
foreach ($matches as $key=>$value) {
echo $key . ", " . $value . "<br>";
}
since you're not worrying about validating the HTML, you might try using strip_tags() on the text first to clear out most of the cruft.
Then you can search for an expression like
"/\<img .+ \/\>/i"
The backslashes escape special characters like <,>,/.
.+ insists that there be 1 or more of any character inside the img tag
You can capture part of the expression by putting parentheses around it. e.g. (.+) captures the middle part of the img tag.
When you decide what part of the middle you wish specifically to capture, you can modify the (.+) to something more specific.
<?php
/* PHP Simple HTML DOM Parser # http://simplehtmldom.sourceforge.net */
require_once('simple_html_dom.php');
$html = file_get_html('http://example.com');
$image = $html->find('img')[0]->src;
echo "<img src='{$image}'/>"; // BOOM!
PHP Simple HTML DOM Parser will do the job in few lines of code.