Replace only the path of image usig preg_replace in php - php

I am using preg_replace to alter the image path only except image name like:
<img src="http://www.ByPasspublishing.com/uploadedImages/TinyUploadedImage/SOC_Aggression_Define_Fig Territorial Aggression.jpg" />
to
Below is the code I have tried but it replace the total path. Please help me to solve this problem:
$html = preg_replace('/<img([^>]+)src="([^"]+)"/i','<img\\1src="newfolder"',$slonodes[0]->SLO_content);
Another thing is that $slonodes[0]->SLO_content returns an HTML content within which I have to find the image and replace the path of that image so the path will not be same.
Thanks in advance.

Alternatively, you could use an HTML Parser for this task, DOMDocument in particular:
$html = '<img src="http://www.ByPasspublishing.com/uploadedImages/TinyUploadedImage/SOC_Aggression_Define_Fig Territorial Aggression.jpg" />';
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$img = $dom->getElementsByTagName('img')->item(0);
$new_src = 'newfolder/' . basename($img->getAttribute('src'));
$img->setAttribute('src', $new_src);
echo $dom->saveHTML($img);

Why use regex? O.o
You can do something like this:
$path = "http://www.ByPasspublishing.com/uploadedImages/TinyUploadedImage/SOC_Aggression_Define_Fig Territorial Aggression.jpg";
$pathNew = "newfolder/".substr(strrchr($path, "/"), 1);
print $pathNew;
I cut on the last "/" char and then concatenate Strings and chars to obtain your desired output.

Related

Regex preg_replace find image in string WITH img attributes

I'm trying to find ALL images in my blog posts with regex. The code below returns images IF the code is clean and the SRC tag comes right after the IMG tag. However, I also have images with other attributes such as height and width. The regex I have does not pick that up... Any ideas?
The following code returns images that looks like this:
<img src="blah_blah_blah.jpg">
But not images that looks like this:
<img width="290" height="290" src="blah_blah_blah.jpg">
Here is my code
$pattern = '/<img\s+src="([^"]+)"[^>]+>/i';
preg_match($pattern, $data, $matches);
echo $matches[1];
Use DOM or another parser for this, don't try to parse HTML with regular expressions.
$html = <<<DATA
<img width="290" height="290" src="blah.jpg">
<img src="blah_blah_blah.jpg">
DATA;
$doc = new DOMDocument();
$doc->loadHTML($html); // load the html
$xpath = new DOMXPath($doc);
$imgs = $xpath->query('//img');
foreach ($imgs as $img) {
echo $img->getAttribute('src') . "\n";
}
Output
blah.jpg
blah_blah_blah.jpg
Ever think of using the DOM object instead of regex?
$doc = new DOMDocument();
$doc->loadHTML('<img src="http://example.com/img/image.jpg" ... />');
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
echo $tag->getAttribute('src');
}
You'd better to use a parser, but here is a way to do with regex:
$pattern = '/<img\s.*?src="([^"]+)"/i';
The problem is that you only accept \s+ after <img. Try this instead:
$pattern = '/<img\s+[^>]*?src="([^"]+)"[^>]+>/i';
preg_match($pattern, $data, $matches);
echo $matches[1];
Try this:
$pattern = '/<img\s.*?src=["\']([^"\']+)["\']/i';
Single or double quote and dynamic src attr position.

How to exract img src using preg_match

I have different format array of html
[amp;src]=>image, anotherone [posthtml]=>image2, anothertwo [nbsp;image3
How to extract img and text using common preg_match() by which we can get perfect image src and text from html. If it is not possible using preg_match(), is there another way to fix it.
If any one know please, reply it. How to fix it.
I need your hand.
The recommended way is to use DOM
$dom = new DOMDocument;
$dom->loadHTML($HTML);
$images = $dom->getElementsByTagName('img');
foreach($images as $im){
$attrs = $imgages->attributes();
$src = $attrs->getNamedItem('src')->nodeValue
}
Using Regular expression:
preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $html, $m);
print_r($m);

Getting content of partial html in DomDocument

I have a string:
$string = 'some text <img src="www">';
I want to get the image source and the text.
Here is what I have:
$doc= new DOMDocument();
$doc->loadHTML($string);
$nodes=$doc->getElementsByTagName ('img');
From $nodes->item(0) I get the image source.
How can I get the the "some text"?
textContent, or with DOMXPaths $xpath->query('//text()')
For simple cases like this, try:
$doc->documentElement->textContent
You could make it like jQuery in javascript. Wrap the whole string with anything, and get this. Then you can get the TextNode, which contains this text.
$string = 'some text <img src="www">';
$string = '<div id="wrapper">' . $string . '</div>';
$nodes = $doc->getElementById('wrapper');

Replace strings possible with output of PHP file_get_contents?

I'm using PHP to get content from an external website.
I want to know if it's possible to find and replace strings from the output so I can make all links absolute.
I need to convert "/ and '/ to "$url/
If it's possible to do that, I can figure out how to do the rest. I don't know if it's possible though.
Thanks
For simple string replacement, use str_replace(), eg
$html = str_replace(array("'/", '"/'), array("'$url/", '"' . $url . '/'), $html);
If you're after a more robust solution, I'd suggest loading the HTML string into a DOMDocument, loop over all the tags with href starting with / and change the attribute of each before writing out the HTML.
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$anchors = $xpath->query('//*[starts-with(#href, "/")]');
foreach ($anchors as $anchor) {
$href = $anchor->getAttribute('href');
$anchor->setAttribute('href', $url . $href);
}
$html = $doc->saveHTML();
You'll probably want to do the same for tags with src attributes.
You could also use preg_replace(), though the DOMDocument parsing is the most robust.

Using regex to remove HTML tags

I need to convert
$text = 'We had <i>fun</i>. Look at this photo of Joe';
[Edit] There could be multiple links in the text.
to
$text = 'We had fun. Look at this photo (http://example.com) of Joe';
All HTML tags are to be removed and the href value from <a> tags needs to be added like above.
What would be an efficient way to solve this with regex? Any code snippet would be great.
First do a preg_replace to keep the link. You could use:
preg_replace('(.*?)', '$\2 ($\1)', $str);
Then use strip_tags which will finish off the rest of the tags.
try an xml parser to replace any tag with it's inner html and the a tags with its href attribute.
http://www.php.net/manual/en/book.domxml.php
The DOM solution:
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach($xpath->query('//a[#href]') as $node) {
$textNode = new DOMText(sprintf('%s (%s)',
$node->nodeValue, $node->getAttribute('href')));
$node->parentNode->replaceChild($textNode, $node);
}
echo strip_tags($dom->saveHTML());
and the same without XPath:
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach($dom->getElementsByTagName('a') as $node) {
if($node->hasAttribute('href')) {
$textNode = new DOMText(sprintf('%s (%s)',
$node->nodeValue, $node->getAttribute('href')));
$node->parentNode->replaceChild($textNode, $node);
}
}
echo strip_tags($dom->saveHTML());
All it does is load any HTML into a DomDocument instance. In the first case it uses an XPath expression, which is kinda like SQL for XML, and gets all links with an href attribute. It then creates a text node element from the innerHTML and the href attribute and replaces the link. The second version just uses the DOM API and no Xpath.
Yes, it's a few lines more than Regex but this is clean and easy to understand and it won't give you any headaches when you need to add additional logic.
I've done things like this using variations of substring and replace. I'd probably use regex today but you wanted an alternative so:
For the <i> tags, I'd do something like:
$text = replace($text, "<i>", "");
$text = replace($text, "</i>", "");
(My php is really rusty, so replace may not be the right function name -- but the idea is what I'm sharing.)
The <a> tag is a bit more tricky. But, it can be done. You need to find the point that <a starts and that the > ends with. Then you extract the entire length and replace the closing </a>
That might go something like:
$start = strrpos( $text, "<a" );
$end = strrpos( $text, "</a>", $start );
$text = substr( $text, $start, $end );
$text = replace($text, "</a>", "");
(I don't know if this will work, again the idea is what I want to communicate. I hope the code fragments help but they probably don't work "out of the box". There are also a lot of possible bugs in the code snippets depending on your exact implementation and environment)
Reference:
strrpos - http://www.php.net/manual/en/function.strrpos.php
replace - http://www.php.net/manual/en/function.str-replace.php
substr - http://php.net/manual/en/function.substr.php
It's also very easy to do with a parser:
# available from http://simplehtmldom.sourceforge.net
include('simple_html_dom.php');
# parse and echo
$html = str_get_html('We had <i>fun</i>. Look at this photo of Joe');
$a = $html->find('a');
$a[0]->outertext = "{$a[0]->innertext} ( {$a[0]->href} )";
echo strip_tags($html);
And that produces the code you want in your test case.

Categories