Регулярное выражение (preg_match) - PullRequest
3 голосов
/ 23 ноября 2011

Это не рабочий код:

<?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 ]

2 голосов
/ 23 ноября 2011

Это также может соответствовать ID12, потому что 3 не пробел, а / of http: / не пробел. Вы можете попробовать:

preg_match_all('/^\S*\/videosite\.com\/(\w+)\S*$/i', $matchWith, $matches);
2 голосов
/ 23 ноября 2011

Итак, вы не хотите, чтобы он отображался, если есть пробелы.Нечто подобное должно работать, не проверял.

preg_match_all('/^\S+?videosite\.com\/(\w+)\S+?$/i', $matchWith, $matches);
1 голос
/ 23 ноября 2011

Вы можете попробовать это.Это работает:

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)
"
0 голосов
/ 23 ноября 2011

Вероятно, было бы проще использовать это регулярное выражение:

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

Я полагаю, что вы имеете в виду пробел до http и пробел после каталога.Таким образом, вы должны использовать символ ^, чтобы указать, что строка должна начинаться с http, и использовать символ $ в конце, чтобы указать, что строка должна заканчиваться символом слова.

...