【问题标题】:Regular Expression (preg_match)正则表达式 (preg_match)
【发布时间】:2012-01-05 00:53:37
【问题描述】:

这是无效的代码:

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

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

【问题讨论】:

  • 根据您的问题,如果它与 reg exp 匹配,它不应该显示任何内容,而您正在做相反的事情。如果开始和结束有空格,则打印。 :)

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


【解决方案1】:

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

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

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

【讨论】:

  • 我得到了我正在寻找的答案。还是非常感谢你:)
【解决方案2】:

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

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】:

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

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

【讨论】:

  • 非常感谢,这就是我要找的答案。
【解决方案4】:

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

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

【讨论】:

  • 太棒了。正是我正在寻找的答案。但是还有另一个问题。如果(在链接中)ID 是 ID123,它只显示 ID12。谢谢
  • 应该是:/\s*\/videosite\.com\/(\w+)\s*/i.
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2014-06-28
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多