Regex replace keyword with different string by loop (PHP) - 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.

Related

extracting link from a string containing html and javascript

I have a string that contains the following:
<img data-bind="defaultSrc: {srcDesktop: 'http://desktoplink', srcMobile: 'http://mobilelink', fallback: 'http://baseurl'}" >
I am trying to extract the srcDesktop contained inside the string. I want my final result to yield me with the link http://desktoplink. What is the best way to achieve that other than str_replace? I have a dataset that contains those strings so I am looking for a formula to extract it in php.
Here is how I have been doing it, but there is got to be a more efficient way:
$string = '<img data-bind="defaultSrc: {srcDesktop: \'http://desktoplink\', srcMobile: \'http://mobilelink\', fallback: \'http://baseurl\'}" >';
$test = explode(" ",$string);
echo "<br>".str_replace(",","",str_replace("'","",$test['3']));
You can use preg_match
$string = '<img data-bind="defaultSrc: {srcDesktop: \'http://desktoplink\', srcMobile: \'http://mobilelink\', fallback: \'http://baseurl\'}" >';
preg_match('/.*\bsrcDesktop:\s*(?:\'|\")(.*?)(?:\'|\").*/i', $string, $matches);
if (isset($matches[1])) {
echo trim($matches[1]);
}
you can use DOMDocument and json_decode to get this value, if you can change the code to the code below (added some '-signs):
$string = "<img data-bind=\"'defaultSrc': {'srcDesktop': 'http://desktoplink', 'srcMobile': 'http://mobilelink', 'fallback': 'http://baseurl'}\" >";
$doc = new DOMDocument();
$doc->loadHTML($string);
$data = str_replace('\'','"',$doc->getElementsByTagName('img')[0]->getAttribute('data-bind'));
$json = json_decode('{'.$data.'}');
var_dump($json->defaultSrc->srcDesktop);

issus with emoji in array

In this code, when I use ":-)" emoji doesn't show in output.
But when use "1f60a" OR "1f60c" OR "e252" emoji are shown. What's the problem?
<?php
$emoji_url = "http://coremobile.ir/images_smileys";
$emoji_style = "";
$emoji_code = array(
":-)",
"1f60a",
"1f60c",
"e252"
);
$emoji_img = array(
'<img src="'.$emoji_url.'/1f60a.png" '.$emoji_style.'>',
'<img src="'.$emoji_url.'/1f60a.png" '.$emoji_style.'>',
'<img src="'.$emoji_url.'/1f60c.png" '.$emoji_style.'>',
'<img src="'.$emoji_url.'/e252.png" '.$emoji_style.'>'
);
$ret = 'This Test :-) 1f60a';
$ret = str_replace($emoji_code, $emoji_img, $ret);
echo $ret;
?>
This should work for you:
(Just use strtr() instead of str_replace(), so that it won't go through the string multiple times)
$ret = strtr($ret, array_combine($emoji_code, $emoji_img));
output:
This Test
The otherone didn't worked, because it replaced every match for the first replacement and then the second and so on.
0 replaced:
This Test :-) 1f60a
//^^^ match
first replaced:
This Test <img src="http://coremobile.ir/images_smileys/1f60a.png" > 1f60a
//^^^^^ match ^^^^^ match
second replaced:
This Test <img src="http://coremobile.ir/images_smileys/<img src="http://coremobile.ir/images_smileys/1f60a.png" >.png" > <img src="http://coremobile.ir/images_smileys/1f60a.png" >

Deleting img tag from string

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

PHP Using str_replace along with preg_replace

I have a string of comma separated values that comes from a database, which actually are image paths. Like so:
/images/us/US01021422717777-m.jpg,/images/us/US01021422717780-m.jpg,/images/us/US01021422717782-m.jpg,/images/us/US01021422718486-m.jpg
I then do like below, to split them at the , and convert them into paths for the web page.
preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1">', $a)
Works well, but in one place further in my page, I need to change the -m to -l (which means large)
When I do like below (put a str_replace inside the preg_replace), nothing happens. How can I do something like this?
preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1" data-slide="'.str_replace('-m','-l','$1').'">', $a)
You're putting the str_replace() call in the output pattern for the preg_replace() call. That means preg_replace() is treating it as literal text.
What you want is something like this:
$imgtag = preg_replace(match, replacement, $a);
$imgtag = str_replace('-m','-l',$imgtag);
But, in my opinion it would be safer and easier to debug this stuff if you changed the order of your replacement operations, something like this:
foreach ($path in explode(",", $a)) {
$path = str_replace('-m','-l',$path);
$imgtag= sprintf ('<img class="gallery" src="%s">', $path);
/* do something with the $imgtag */
}
That way you don't have to whistle into your modem :-) to program that regexp.
Use str_replace on preg_replace return
$large = str_replace('-m','-l', preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1">', $a));
Output will be
<img class="gallery" src="/images/us/US01021422717777-l.jpg">
<img class="gallery" src="/images/us/US01021422717780-l.jpg">
<img class="gallery" src="/images/us/US01021422717782-l.jpg">
<img class="gallery" src="/images/us/US01021422718486-l.jpg">
Use preg_replace_callback():
preg_replace_callback(
'~\s?([^\s,]+)\s?(?:,|$)~',
function (array $matches) {
$src = $matches[1]; // this is "$1"
$slide = str_replace('-m', '-l', $matches[1]);
return '<img class="gallery" src="'.$src.'" data-slide="'.$slide.'">';
},
$a
);
Instead of the replace expression, preg_replace_callback() gets as its second argument a function that receives the list of matched expressions and returns the replacement string.
Actually your str_replace is simply invoked before preg_replace is invoked. Result of str_replace is then passed as argument to preg_replace.
What I could suggest is using preg_replace_callback:
function replace_img($match)
{
return '<img class="gallery" src="' .
$match[1] .
'" data-slide="' .
str_replace('-m','-l',$match[1]) .
'">';
}
preg_replace_callback('~\s?([^\s,]+)\s?(?:,|$)~','replace_img', $a);
If you need two separate outputs from each comma-separated value, I would write a pattern that stores the fullstring match and the substrings on either side of the m in each file.
*note: I match the trailing - in the first capture group and the leading . in the second capture group for minimal assurance of accuracy. This is somewhat weak validation; you can firm it up if your project requires it by adding literal or more restrictive pattern components in the capture groups.
Code: (Demo)
$csv='/images/us/US01021422717777-m.jpg,/images/us/US01021422717780-m.jpg,/images/us/US01021422717782-m.jpg,/images/us/US01021422718486-m.jpg';
if(preg_match_all('~([^,]+-)m(\.[^,]+)~',$csv,$out,PREG_SET_ORDER)){
foreach($out as $m){
$mediums[]="<img class=\"gallery\" src=\"{$m[0]}\">";
$larges[]="<img class=\"gallery\" src=\"{$m[0]}\" data-slide=\"{$m[1]}l{$m[2]}\">";
}
}
var_export($mediums);
echo "\n\n";
var_export($larges);
Output:
array (
0 => '<img class="gallery" src="/images/us/US01021422717777-m.jpg">',
1 => '<img class="gallery" src="/images/us/US01021422717780-m.jpg">',
2 => '<img class="gallery" src="/images/us/US01021422717782-m.jpg">',
3 => '<img class="gallery" src="/images/us/US01021422718486-m.jpg">',
)
array (
0 => '<img class="gallery" src="/images/us/US01021422717777-m.jpg" data-slide="/images/us/US01021422717777-l.jpg">',
1 => '<img class="gallery" src="/images/us/US01021422717780-m.jpg" data-slide="/images/us/US01021422717780-l.jpg">',
2 => '<img class="gallery" src="/images/us/US01021422717782-m.jpg" data-slide="/images/us/US01021422717782-l.jpg">',
3 => '<img class="gallery" src="/images/us/US01021422718486-m.jpg" data-slide="/images/us/US01021422718486-l.jpg">',
)

Replace string with different strings containing pattern

Say you have a string like
$str = "<img src='i12'><img src='i105'><img src='i12'><img src='i24'><img src='i15'>....";
is it possible to replace every i+n by the nth value of an array called $arr
so that for example <img src='i12'> is replaced by <img src='$arr[12]'>.
If I were you, I'd simply parse the markup, and process/alter it accordingly:
$dom = new DOMDocument;
$dom->loadHTML($str);//parse your markup string
$imgs = $dom->getElementsByTagName('img');//get all images
$cleanStr = '';//the result string
foreach($imgs as $img)
{
$img->setAttribute(
'src',
//get value of src, chop of first char (i)
//use that as index, optionally cast to int
$array[substr($img->getAttribute('src'), 1)]
);
$cleanStr .= $dom->saveXML($img);//get string representation of node
}
echo $cleanStr;//echoes new markup
working demo here
Now in the demo, you'll see the src attributes are replaced with a string like $array[n], the code above will replace the values with the value of an array...
I would use preg_replace for this:
$pattern="/(src=)'\w(\d+)'/";
$replacement = '${1}\'\$arr[$2]\'';
preg_replace($pattern, $replacement, $str);
$pattern="/(src=)'\w(\d+)'/";
It matches blocks of text like src='letter + digits'.
This catches the src= and digit blocks to be able to print them back.
$replacement = '${1}\'\$arr[$2]\'';
This makes the replacement itself.
Test
php > $str = "<img src='i12'><img src='i105'><img src='i12'><img src='i24'><img src='i15'>....";
php > $pattern="/(src=)'\w(\d+)'/";
php > $replacement = '${1}\'\$arr[$2]\'';
php > echo preg_replace($pattern, $replacement, $str);
<img src='$arr[12]'><img src='$arr[105]'><img src='$arr[12]'><img src='$arr[24]'><img src='$arr[15]'>....

Categories