for example i have a text like
<p>
Quis vel accusantium libero. Suscipit officiis culpa
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
libero quia ad.
</p>
and i want to check if the string has any data:image
then truncate only this part so max char of 50, so the results become
<p>
Quis vel accusantium libero. Suscipit officiis culpa
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH...">
libero quia ad.
</p>
am not sure how exactly to achieve that with preg_replace
and "data:image.+?"
pattern
You can do that in different ways, with preg_match
(_all), preg_split
, etc.
But with the preg_replace
will work like this: run to see
<?php
$text='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
$result=preg_replace('/(?<=data:image.{50}).*/', '', $text);
echo $result;
src
attribute on img tags, then you can tokenize the raw HTML string, and then perform regex replaces, but that approach is going to be painful if you decide you want to do other modifications. You may end up re-inventing the wheel, when you could have just used a real HTML parser to begin with.<?php
$demostring = '
<p>
Quis vel accusantium libero. Suscipit officiis culpa
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
libero quia ad.
</p>
';
function ctf0_truncate($vinput){
return( preg_replace('/(data:image.{50})(.*)/', '$1', $vinput) );
}
function ctf0_parse($text, $chars = 50) {
if (strpos($text, 'data:image') !== FALSE){
$tokens = explode('"',$text);
$tokens = array_map("ctf0_truncate",$tokens);
$vout = implode('"',$tokens);
} elseif( True ) {
$vout = $text;
}
return $vout;
}
$myresult = ctf0_parse($demostring);
print($myresult);
<p>
Quis vel accusantium libero. Suscipit officiis culpa
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALA">
libero quia ad.
</p>