2

Ok I need help with thisone: I need something that matches backwards I think? Like "match backwards from '.no' until first space" I need to replace some text with links.

See examples of what im trying to accomplish below:

blabla hello www.test.no bla => blabla hello <a href="www.test.no">www.test.no</a> bla

blabla hello test.no bla => blabla hello <a href="test.no">test.no</a> bla

blabla hello http://www.test.no bla => blabla hello <a href="http://www.test.no">http://www.test.no</a> bla

Anyone?

2
  • I don't understand - the output string you expect for all the variations appears to be the same as the input string. What transformation are you trying to do? What is the point of the match? Commented Aug 20, 2011 at 20:26
  • Ah that makes more sense. Well edited. Commented Aug 20, 2011 at 20:28

3 Answers 3

2

I still don't understand what exactly you need, because your example is not explained very well, but here goes:

preg_replace('/[^ ]+\.no/', '<a href="$0">$0</a>', $your_text);

Example code: http://ideone.com/H4iFD

EDIT: there you go:

preg_replace("~(http://)?([^ ]+\.no)~", '<a href="http://$2">$2</a>', $your_text);

Example code: http://ideone.com/3OLfI

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

2 Comments

thank you! is it also possible to insert 'http://' in the replacement, only if there is no 'http://' in the match?
@Kristian regex is traditionally delimited by /, but in php it can be just about any weird character. I was not sure whether I had to escape the // I introduced inside the second regex, so to be sure I changed the delimiter to ~. Note: the / and ~ are the most common delimiters.
0

You have no chance to know if second line is really a link without trying to ping it (for example with curl).

But you can do third with

preg_replace('~(http://.*?) ~', '<a href="$1">$1</a>', $text);

Comments

0
$linked = preg_replace('%(?://)?([a-z0-9_\-.]+?\.no)%i', "<a href='http://$1'>$1</a>", $input);

1 Comment

this works for all except the third one. that will become http://http://www.test.no :>

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.