1

I wan't to replace

[a href='url']link[/a]

to

<a href='url'>link</a>

I am using $line = str_replace("[a href='+(.*)+']", "<a href='+(.*)+' >", $line); is not working.

5 Answers 5

7

Why not just use:

$search = array('[', ']');
$replace = array('<', '>');

$line = str_replace($search, $replace, $line);
Sign up to request clarification or add additional context in comments.

3 Comments

Will work for simple cases. Once you get [] in the url or link it'll fail (by replacing too much)
You're right, but the OP asked for a specific usecase. If he really only needs to do that this approach might be easier to read than a regex.
Sure. Your answer is in fact correct, just limited to simple case (which might be enough for what OP needs).
2

You have to use a regular expression to do this

$line = preg_replace('~\\[a +href=\'([^\']+)\'\\]([^\\[]+)\\[/a\\]~', '<a href="$1">$2</a>', $line);

5 Comments

"You have to use a regular expression" No, you don't have to.
if he simply want to do this, this is the fastest way - sure, you could something different
Well... once you get to nested tags, you most likely would want to. Of course it's not like you really need to... you can just as well write a compiler.
@Philipp can you also tell me, the syntax for the same work in javascript??
try newval = varname.replace(/\[a +href='([^']+)'\]([^\[]+)\[\/a\]/, '<a href="$1">$2</a>')
1

simply use

$string = str_replace(array('[', ']'), array('<', '>'), $string);

Comments

0

This is a great tutorial http://www.youtube.com/watch?v=x9VLWlQhNtM it shows you how to make a small templating engine and it covers what your asking

Comments

0

Try this :

$str = "[a href='url']link[/a]";
$new_str  = preg_replace('/\[a href=\'(.*)\'\](.*)\[\/a\]/','<a href=\'$1\'>$2</a>',$str);
echo $new_str;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.