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.

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;

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.