Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression (preg_match)

This is the not working code:

<?php
$matchWith = "  http://videosite.com/ID123 ";
preg_match_all('/\S\/videosite\.com\/(\w+)\S/i', $matchWith, $matches);  
foreach($matches[1] as $value)
{  
    print '<a href="http://videosite.com/'.$value.'">Hyperlink</a>';        
}  
?>

What I want is that it should not display the link if it has a whitespace before or after. So now it should display nothing. But it still displays the link.

like image 476
Helena Avatar asked Aug 19 '26 21:08

Helena


2 Answers

This can also match ID12, because 3 is not an space, and the / of http:/ is not a space. You can try:

preg_match_all('/^\S*\/videosite\.com\/(\w+)\S*$/i', $matchWith, $matches);
like image 188
Arend Avatar answered Aug 21 '26 11:08

Arend


So, you don't want it to display if there's whitespaces. Something like this should work, didn't test.

preg_match_all('/^\S+?videosite\.com\/(\w+)\S+?$/i', $matchWith, $matches);
like image 39
William Stearns Avatar answered Aug 21 '26 12:08

William Stearns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!