Php 正则表达式(preg_匹配)

Php 正则表达式(preg_匹配),php,regex,preg-match,preg-match-all,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>

这是无效代码:

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

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

因此,如果有空格,您不希望它显示。像这样的东西应该有用,但没有测试

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

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

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

你可以试试这个。它的工作原理是:

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)
"

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

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

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

根据您的问题,如果它与reg exp匹配,则不应显示任何内容,而您的操作正好相反。如果“开始”和“结束”中有空格,则打印。:)令人惊叹的。这正是我想要的答案。但还有另一个问题。如果(在链接中)ID为ID123,则仅显示ID12。谢谢应该是:/\s*\/videosite\.com\/(\w+)\s*/i。非常感谢,这就是我一直在寻找的答案。多么棒的答案!难以置信的然而,我是一个非常愚蠢的noob,不能将此代码集成到我的代码中。但另一个代码起作用了,但还是要感谢你们,你们太棒了。我已经找到了我一直在寻找的答案。还是非常感谢:)