-3

So I am trying to figure out how I can an input such as

[url=value]

and turn it into

<a href="value">

Of course, I want to preserve that value. Thanks for the help!

Ultimately I want to be able to feed in any target and replacement, including [email=value] to <a href="mailto:value">.

So far I have:

$before = explode($fix['before'],"value");
$after = explode($fix['after'],"value");
preg_replace('/\\'.$before[0].'(.+?)'.'\\'.$before[1].'/', $after[0].'\1'.$after[1], $post);

2 Answers2

1

You can use regular expressions. In PHP, you can use the preg_replace function. An example regex you could use for that would be /\[url=(.+)\]/ and the replacement would be <a href="$1">

Ditmar Wendt
  • 668
  • 4
  • 15
  • You'll need to define that `.+` as group `(.+)` or the reference `$1` won't work – kero Feb 20 '14 at 00:17
  • Yeah I have gotten that far. What I want to ultimately be able to do though is use a variable containing `[url=value]` or `[email=value]` etc and feed it into the script and have it process. So far I have `$before = explode($fix['before'],"value"); $after = explode($fix['after'],"value"); preg_replace('/\\'.$before[0].'(.+?)'.'\\'.$before[1].'/', $after[0].'\1'.$after[1], $post);` – user1748794 Feb 20 '14 at 00:20
1

You could use this regex:

\[(.*?)=([^\]]+)]

Working regex example:

http://regex101.com/r/nL6lH9

Test string:

[url=http://www.web.com/test.php?key=valuepair]

Matches:

match[1]: "url"
match[2]: "http://www.web.com/test.php?key=valuepair"

PHP:

$teststring = '[url=http://www.web.com/test.php?key=valuepair]';

preg_match('/\[(.*?)=([^\]]+)]/', $teststring, $match);

// So you could test if $match[1] == 'url' or 'email' or etc.

switch ($match[1]) {
    case "url":
        $output = '<a href="'.$match[2].'">Link</a>';
        break;
    case "email":
        $output = '<a href="mailto:'.$match[2].'">Send Email</a>';
        break;
}
echo str_replace($teststring, $output, $teststring);

Output:

<a href="http://www.web.com/test.php?key=valuepair">Link</a>
Bryan Elliott
  • 4,055
  • 2
  • 21
  • 22