Forum Moderators: coopster
$txt = preg_replace("#(^¦[\n ])([\w]+?:youtube[\w]+[^ \"\n\r\t<]*)#ise", "<a href=\"http://www.youtube.com/v/$1\">watch video</a>", $txt );
Attention, because th link coould be on a phrase or is written difernt way, like:
bla bla [youtube.com...] blabla
or bla bla [fr.youtube.com...] bla bla
or bla bla www.youtube.com/watch?v=dOrKLUlh-To&feature= bla bla
but in all cases the word "youtube" is present. So matchin *youtube* only is possible to convert it in a link? and how?
First thing I'd do is remove newlines, this will simplify the task.
$txt = preg_replace('/[\s]+/',' ',$txt);
I don't use # as delimiters simply because those are also comment characters, matter of choice.
Using \s instead of \n\r will nix double spaces, too, which is generally good.
I am GUESSING this is a plain text value you want to convert to a link, correct?
$pre_link = '<a href=\"http://www.youtube.com/v/';
$post_link = '">';
$close_link = 'watch video</a>';
I'd do it like this:
- look for youtube literal
- look for =
- look for first occurrence of &, if not found, it's the end of pattern so this will be a space or nothing at all.
What's between = and & is what I want.
$txt= preg_replace('/\s*.*?youtube[^=]+=([^\&]+)[\&\s]*/i',"$pre_link$1$post_link$close_link",$txt);
\s* = on the off chance it's the very first line, zero or more for the start, but most likely they will start with a space (newlines converted to spaces in first reg).
.*? = zero or more of any character, with quantifier to avoid greedy pattern matching
youtube = duh. :-)
[^=]+ = one or more of anything NOT a =
= = literal =
([^\&]+) = one or more of anything NOT an ampersand, store this in $1
[\&\s]* = zero or more ampersands or a space. This may not have the ampersand so it's possible it will end with a space, but like the beginning of the pattern, this may be the end of the line.
Untested, may not work, but it's worth a shot. :-)
(*)To get the video code I use: preg_match("/v=([^(\&¦$)]*)/", $txt, $matches);
$yt_id = $matches[1];
so, $txt= preg_replace('/\s*.*?youtube[^=]+=([^\&]+)[\&\s]*/i',"<a href=\"http://www.youtube.com/v/$yt_video\">Watch video</a>",$txt);