wordpress - How to add image link as hyperlink to all images in content using preg_replace? -
i want change hyperlink of images post in content image link. can edit link using
function add_image_responsive_class($content) { global $post; $pattern ="~<a .*?>\s*<img(.*?)class=\"(.*?)\"(.*?)>\s*</a>~i"; $replacement = '<a href="$1"><img$1class="$2"$3></a>'; $content = preg_replace($pattern, $replacement, $content); return $content; } add_filter('the_content', 'add_image_responsive_class');
but cant copy image link hyperlink.
for example:
now have this:
<a href="http://www.mywebsite.com/mypage"><img src="imagelink"></a>
i want change to:
<a href="imagelink"><img src="imagelink"></a>
okay, there few ways can this. i'll show 1 easy way, know can customize down finer granularity. process same, though.
basically we're going split string chunks , save each chunk putting set of parenthesis around it. can interchange chunks please.
let's take string , divide different parts.
<a href="http://www.mywebsite.com/mypage"><img src="imagelink"></a> |---1---||---------------2-------------||-----3----||---4---||--5-|
really want here replace #2 #4. order be:
#1 #4 #3 #4 #5
this pretty easy achieve preg_replace
, here's how:
$link_text = '<a href="http://www.mywebsite.com/mypage"><img src="imagelink"></a>'; // add parenthesis around each item want capture $link_text = preg_replace('~(<a href=")(.*?)("><img src=")(.*?)("></a>)~i', '$1$4$3$4$5', $link_text); print $link_text;
that give following:
<a href="imagelink"><img src="imagelink"></a>
that being said, can divide string wish ... doesn't have how did it. concept same. each set of parenthesis captures 1 item , gives number. can plug in number other part of string.
here working demo:
Comments
Post a Comment