正则表达式(preg_match)

时间:2011-11-23 18:16:50

标签: php regex preg-match preg-match-all

这是无效的代码:

<?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>';        
}  
?>

我想要的是,如果链接之前或之后有空格,则不应显示该链接。 所以现在它什么都不显示。但它仍然显示链接。

4 个答案:

答案 0 :(得分:2)

所以,如果有空格,你不希望它显示。这样的事情应该有效,没有测试。

preg_match_all('/^\S+?videosite\.com\/(\w+)\S+?$/i', $matchWith, $matches);

答案 1 :(得分:2)

这也可以匹配ID12,因为3不是空格,而http:/不是空格。你可以尝试:

preg_match_all('/^\S*\/videosite\.com\/(\w+)\S*$/i', $matchWith, $matches);

答案 2 :(得分:1)

你可以试试这个。它有效:

if (preg_match('%^\S*?/videosite\.com/(\w+)(?!\S+)$%i', $subject, $regs)) {
    #$result = $regs[0];
}

但我很肯定在我发布此帖后,您将更新您的问题:)

<强>解释

"
^            # Assert position at the beginning of the string
\S           # Match a single character that is a “non-whitespace character”
   *?           # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\/           # Match the character “/” literally
videosite    # Match the characters “videosite” literally
\.           # Match the character “.” literally
com          # Match the characters “com” literally
\/           # Match the character “/” literally
(            # Match the regular expression below and capture its match into backreference number 1
   \w           # Match a single character that is a “word character” (letters, digits, etc.)
      +            # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
(?!          # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   \S           # Match a single character that is a “non-whitespace character”
      +            # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
\$            # Assert position at the end of the string (or before the line break at the end of the string, if any)
"

答案 3 :(得分:0)

使用这个正则表达式可能更简单:

'/^http:\/\/videosite\.com\/(\w+)$/i'

我相信你指的是http之前的空格,以及目录之后的空格。因此,您应该使用^字符来指示该字符串必须以http开头,并使用末尾的$字符表示该字符串必须以单词字符结尾。