So I'm trying to hack off a few characters at the end of a URL I'm getting from a preg_replace function. However it doesn't seem to be working. I'm not familiar with using these variables in preg_replace (it was just something I found that "mostly" worked).
Here's my attempt:
function addlink_replace($string) {
$pattern = '/<ul(.*?)class="slides"(.*?)<img(.*?)src="(.*?)"(.*?)>(.*?)<\/ul>/is';
$URL = substr($4, 0, -8);;
$replacement = '<ul$1class="slides"$2<a rel=\'shadowbox\' href="'.$URL.'"><img$3src="$4"$5></a>$6</ul>';
return preg_replace($pattern, $replacement, $string);
}
add_filter('the_content', 'addlink_replace', 9999);
Basically I need to remove the last bit of my .jpg file name, so I can show the LARGE image rather than the THUMBNAIL it's generating, but the "$4" doesn't seem to want to be manipulated.
This answer is based off of what you're looking to accomplish in this question with the HTML structure of your other question. The regex that is posted in your question will not match anything other than the first set of
<li>
and<img>
tags , and you've indicated that you need to match all<li>
and<img>
tags within a<ul>
so I've written a larger function to do so.It will wrap all
<img>
tags that are inside of an<li>
within a<ul>
with the class ofslides
with an<a>
with the source being the image's URL with the-110x110
string removed, while preserving the thumbnail source in the<img>
tag.The change of the
<a>
'shref
attribute from what the image had is specifically done on the line$new_img = str_replace('-110x110', '', $img_matches[2][$id]);
if you would like to modify it. If you need to remove anything other than
-110x110
from the URL you may need to change it fromstr_replace
to apreg_replace
, or if you want to remove a specific number of characters from the end of the URL, you could usesubstr
:$new_img = substr($img_matches[2][$id], 0, -12);
Where
-12
is the number of characters you want to remove from the end of the string (it's negative because it's starting at the end).I've posted a working example of this function here.
You may want to consider modifying the source of what is generating this code block, rather than using this regex, as this regex may be hard to maintain in the future if the HTML structure changes.