I'm using this code
echo preg_replace('#\{{2}(.*?)\}{2}#', '<img src="/base/$1">', $input);
To display an input like this:
foo foo {{picture.jpg}} foo
In img html tag.
I would like to add an optional alt attribute in this format:
{{picture.jpg|optional}}
and translate into:
<img src="/base/$1" alt="$2">
only if it is present, without make another preg_replace but only improving the existing one.
How can i do this?
You could use
{{(.+?)(?:\|([^}]+))?}}
See a demo on regex101.com.
Which in PHP, with the help of preg_replace_callback() would be:
<?php
$string = <<<DATA
foo foo {{picture.jpg}} foo
{{picture.jpg|optional}}
DATA;
$regex = '~{{(.+?)(?:\|([^}]+))?}}~';
$string = preg_replace_callback($regex,
function($match) {
if (!empty($match[2])) {
return "<img src='/base/{$match[1]}' alt='{$match[2]}'>";
} else {
return "<img src='/base/{$match[1]}'>";
}
}, $string);
echo $string;
This yields
foo foo <img src='/base/picture.jpg'> foo
<img src='/base/picture.jpg' alt='optional'>
Since you only forbid to use another preg_replace not another regex this works:
preg_replace(['#\{{2}(.*?)\|(.*?)\}{2}#', '#\{{2}(.*?)\}{2}#'], ['<img src="/base/$1" alt="$2">', '<img src="/base/$1">'], $input);
Working example:
function replacer($input) {
return preg_replace(['#\{{2}(.*?)\|(.*?)\}{2}#', '#\{{2}(.*?)\}{2}#'], ['<img src="/base/$1" alt="$2">', '<img src="/base/$1">'], $input);
}
echo replacer('{{picture.jpg}}');
echo replacer('{{picture.jpg|optional}}');
Output:
<img src="/base/picture.jpg">
<img src="/base/picture.jpg" alt="optional">
Related
Would like to do something like this:
$str = '<a>lalala</a>';
echo preg_replace('~<a>(.*)</a>~i','<a>'.str_replace('la','mi',"$1").'</a>',$str);
So it would return:
<a>mimimi</a>
But can't use preg_replace_callback() function. Any simple ideas?
You could use preg_replace_callback() to do specific operations in replacement:
$str = '<a>lalala</a>';
echo preg_replace_callback('~<a>(.*)</a>~i',function($matches){
return '<a>'.str_replace('la','mi',$matches[1]).'</a>';
},$str);
Outputs:
<a>mimimi</a>
Or with preg_match():
$str = '<a>lalala</a>';
if (preg_match('~<a>(.*)</a>~i', $str, $matches)) {
$str = '<a>'.str_replace('la','mi',$matches[1]).'</a>';
};
echo $str;
This is what a typical string looks like
<img src="http://example.com/img/?url=https%3A%2F%2Ffs02.androidpit.info%2Fblog%2Fx36%2F413336.jpg&width=540&mix=c5922-fAndroid">
I want it to become
<img src=https://fs02.androidpit.info/blog/x36/413336.jpg>
How should I proceed?
Try this:
$line = preg_replace_callback(
'/(<img src=")[^\?]*.*\?url=([^&=]+).*(">)/i',
function ($matches) {
return $matches[1] . urldecode($matches[2]) . $matches[3];
},
'<img src="http://example.com/img/?url=https%3A%2F%2Ffs02.androidpit.info%2Fblog%2Fx36%2F413336.jpg&width=540&mix=c5922-fAndroid">'
);
I want write a simple code that convert special words to special link (for wiki plugin), if it's not a link!
For example suppose we have a text "Hello! How are you?!" and
we want convert are to are, but if we have Hello! How are you?! or Hello! How are you?! does not change. Because it's a link.
How can I do it in PHP?! With preg_replace?! How to?
Thanks.
It's easy.
<?php
$string = "Hello! How are you?!";
$stringTwo = "Hello! how are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)/", $string);
}
echo turnTheWordIntoALink($string, 'are', 'http://google.com');
echo turnTheWordIntoALink($stringTwo, 'are', 'http://google.com');
Output:
First function output: Hello! How are you?!
Second function output: Hello! how are you?!
Alternative:
If you want to not detect <a> tags which were closed, you can use this alternative code:
$stringThree = "Hello! how <a href=\"#\">are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)+(.)+(<\/a>)/", $string);
}
echo turnTheWordIntoALink($stringThree, 'are', 'http://google.com') . "\n";
This gives the output: Hello! how <a href="http://google.com">are you?!
this code is about : if there is a some URL in some phrase it will convert to a link
$word = 'hello how are you google.com, wish you good time';
$prg = "/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($prg, $word, $url))
{
echo preg_replace($prg, "<a href=http://$url[0]>{$url[0]}</a>", $word);
}
else
{
echo $word;
}
To better clarify the issue:
I have a HTML code that have some tags. I want some words in that, converted to some links. But if it is a another link does not convert. See below advanced example for special word you that we want linked to the google:
This is a sample text.
Hello?! How are you?!
Are you ready?!
should be convert to:
This is a sample text.
Hello?! How are you?!
Are you ready ?!
Note that the first you changed, but that second you was not changed, because it's in the another <a> tag.
Answer:
Because of this work has issue with regular expression, this problem can solve without regular expression. Here a simple solution is given:
$data = 'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text.';
$from = " is ";
$to = '<a href="http://www.google.com" > '.$from.' </a>';
echo $data;
$data = explode($from, $data);
echo "<br><br>";
echo $data[0];
$diff = 0;
for($i=1; $i<count($data); $i++){
$n = substr_count($data[$i-1], '<a ') + substr_count($data[$i-1], '<A ');
$m = substr_count($data[$i-1], '</a>') + substr_count($data[$i-1], '</A>');
$diff += $n-$m;
if($diff==0)
echo $to.$data[$i];
else
echo $from.$data[$i];
}
I have a image with class 'attachment-fullslideshow'. The code is
<img class="attachment-fullslideshow" src="demo.jpg">
I would like to replace the class from 'attachment-fullslideshow' to 'attachment-fullslideshow quote'.
Please suggest.
You could do something like this:
$str = '<img class="attachment-fullslideshow" src="demo.jpg">';
$str = str_replace('class="attachment-fullslideshow', 'class="attachment-fullslideshow quote', $str);
//Result: <div class="attachment-fullslideshow quote">...</div>
Or with regular expressions:
$str = '<img class="attachment-fullslideshow" src="demo.jpg">';
$str = preg_replace(':class="(.*attachment-fullslideshow.*)":', 'class="\1 quote"', $str);
//Result: <div class="defaultClass myClass">...</div>
Hope this helps!
You could also
$html = '<img class="attachment-fullslideshow" src="demo.jpg">';
$test = preg_replace('/class="(.*?)"/s', 'class="newclass"', $html);
echo $test;
outputs
<img class="newclass" src="demo.jpg">
Mission is to replace all <img> tags in given string with <div> tags and src property as inner text.
In search for the answer I found similar question
<?php
$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
echo $content;
?>
result:
this is something with an (image) in it.
Question: How to upgrade script ant get this result:
this is something with an <div>test.png</div> in it.
This is the kind of problem that PHP's DOMDocument class excels at:
$dom = new DOMDocument();
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('img') as $img) {
// put your replacement code here
}
$content = $dom->saveHTML();
$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content);
echo $content;
<?php
$strings = 'awdaw <img src="http://ua1.us/media/media.jpg" alt="Image" width="100" height="100"> aw <img src="http://ua1.us/media/media1awdwa.jpg"> wawadwad';
preg_match_all('/<img[^>]+>/i', $strings, $images);
foreach ($images[0] as $image) {
preg_match('/src="([^"]+)/i', $image, $replacements);
$replacement = isset($replacements[1]) ? $replacements[1] : (isset($replacements[0]) ? $replacements[0] : "image");
$strings = str_replace($image, $replacement, $strings);
}
echo $strings;