0

I got this regex off of a site forum to look for links in text and replace them with html links so that they are clickable.

the problem came when someone input one of those new youtube links that look like this:

http://youtu.be/djKd189-ag2

What happens is the link is made up to the dash and then -ag2 is left on it's own.

I don't know enough about php regex to even dare alter this to add parsing the dash so I was hoping I could get some help:

$newText = preg_replace('@((http|https)://([\w-.]+)+(:\d+)?(/([\w/_.]*(\?\S+)?)?)?)@', 
             '<a href="$1" class="link1" target="_blank">$1</a>',$text);

I am guessing it's somewhere around the \S+ part

1

1 Answer 1

2
$newText = preg_replace('@((http|https)://([\w-.]+)+(:\d+)?(/([\w/_-.]*(\?\S+)?)?)?)@', 
             '<a href="$1" class="link1" target="_blank">$1</a>',$text);

You need just a '-' where it's written '[\w/_.]'

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

1 Comment

I tried to use that but I am getting an error from php : PHP Warning &#039;yii\base\ErrorException&#039; with message &#039;preg_replace(): Compilation failed: range out of order in character class at offset 42&#039;

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.