I want to transform a certain number of characters by a string in PHP from a text :
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fringilla tincidunt justo sed hendrerit. Vivamus [im::17,I] elit id accumsan pulvinar. Fusce ac lacus arcu. Nullam imperdiet imperdiet eros, [im::31,R] congue libero. Aliquam non bibendum nisi. Nunc pretium feugiat nunc ut volutpat. Maecenas finibus viverra justo, quis luctus [im::11,L] facilisis vel.
So what I try to do is to replace this :
[im::31,R]
By this:
<img src='img_31_0px.jpg' style='text-align:right;'/>
I got an array for the style inherit, left, right, center, this is not my difficulty.
This is my actual function:
function showimg($txtimg) {
$fullstr = str_replace("[im::17,I]", "<img src='img_17_0px.jpg' style='text-align:inherit;'/>", $txtimg);
return ($fullstr);
}
As you can see, it's static for the moment, and not dynamic. I am looking on http://www.regexr.com/ to try something but it doesn't leed me anywhere.
Can you guys help me with my case, or leed me in the good direction at least? Thanks.
Well, to keep the alignment you'll need a callback:
function showimg($m) {
$dir = array('I'=>'inherit','R'=>'right','L'=>'left');
return '<img src="img_'.$m[1].'_0px.jpg" style="text-align:'.$dir[$m[2]].';"/>';
}
$result = preg_replace_callback('/\[im::([0-9]+),(I|R|L)\]/', 'showimg', $txtimg);
I'm going to assume that numbers will be 1 or 2 digits for this. I have the regex capture that tag and replace the digits found within
preg_replace('/\[im::(\d{1,2}),\w\]/', '<img src="img_\\1_0px.jpg" style="text-align:inherit;"/>', $str);
This is how i far I got:
function showimg($txtimg) {
$fullstr = str_replace("[im::", "<img src='img_", $txtimg);
$fullstr = str_replace(",I]", "_0px.jpg' style='max-width:100%; text-align:inherit;'/>", $fullstr);
return ($fullstr);
}
I finaly used the answer of AbraCadaver