Jump to content

Replace each occurence between brackets with code


giraffemedia

Recommended Posts

Hi,

 

I'm trying to write a function that finds all text within a string beginning with [[ and ending with ]] and manipulates the content between them.

 

For example:

 

This is some sample text and [[Debenhams||debenhams.com]] and this is a bit more sample text that [[sainsburys||sainsburys.com]]

 

What I want to do is turn the bits between the brackets into links, using the first piece of text as the link name and the second as the link url.

 

What I need is a function that replaces every instance of the bracketed code with the link text.

 

Here is what I have so far which is working.

 

function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}

$fullstring = "Here is some link text [[Debenhams||debenhams.com]] my";

$parsed = explode("||", get_string_between($fullstring, "[[", "]]"));

echo '<a href="http://www.'.$parsed[1].'" title="Visit the '.$parsed[0].' website" target="_blank">'.$parsed[0].'</a>'; // (result = link to Debenhams)

 

What I cannot figure out is how to write a function that  searches a string and replaces all the bits between the brackets with the links.

 

I'd really appreciate some help please.

Link to comment
Share on other sites

You would use preg_replace to directly do this -

<?php
$str = "This is some sample text and [[Debenhams||debenhams.com]] and this is a bit more sample text that [[sainsburys||sainsburys.com]]";

$str = preg_replace("/\[\[(.*?)\|\|(.*?)\]\]/is","<a href='http://www.$2' title='Visit the $1 website' target='_blank'>$1</a>",$str);
echo $str;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.