0

I have a string:

$string = '<a href="/news/blablalba">some text</a>';

I need to add target="_blank" attribute inside tag above and http://mysite.kz before /news/blablabla.

preg_replace("/<a href=\"\/(.*)\">(.*)<\/a>/iU", "<a target=\"_blank\" href=\"\/(.*)\">(.*)\">(.*)<\/a>", $string);

code above won't works. Help please!

UPDATED

Solved this task:

$match1 = preg_replace("/<a href=\"\/(.*)\">(.*)<\/a>/i", "<a target=\"_blank\" href=\"http://nashmir.kz/$1\">$2</a>", $string);

1 Answer 1

2

preg_replace('/^<a\s+(href=")(\/news\/)/i', '<a target="_blank" $1http://mysite.kz$2')

Rule of thumb: you only need to match what is necessary. Except in very rare cases, you never need to match the whole input.

Sign up to request clarification or add additional context in comments.

5 Comments

@Heihachi see my edit as well: you still try and match more than necessary for the job at hand.
No, look after <a\s+, you try and match h, then r, then..., then a quote and then another quote. Similarly, at the end of the regex, you try and match two slashes after the s of news.
By the way, $1, $2 means values from rounded brackets in regexp?
I suppose you mean (). In regex language, this is called a grouping. It has two properties: it captures so that you can use backreferences (which $1 and $2 are), and makes the contained regex atomic wrt quantifiers such as *, +, etc.
@ridgerunner I didn't know what it do, but I deleted it, thanks for the info ;) I see we have the same references.

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.