【问题标题】:PHP Regex - find word and get everything until characterPHP Regex - 查找单词并获取所有内容,直到字符
【发布时间】:2017-04-14 00:28:06
【问题描述】:

我试图找到一个匹配字符串的正则表达式模式,并返回该字符串之后的所有内容,直到'/'。我目前有:

'/forums\/topic\/\s*([^\/]*)/u'

但这会返回所有内容,包括“论坛/主题/”

示例:字符串:

equest lorem ipsum dawhdk scripts. Problem: a href="__;_base_url_j;p_i;oj/index.php?/forums/topic/975-example-maps-to-local-rating/" then does something,

我只需要“975-example-maps-to-local-rating”

【问题讨论】:

  • 简化你的表达方式:使用/以外的东西作为模式分隔符,那么你就不必在模式中转义它了。
  • 你的正则表达式在这里工作:regex101.com/r/vv6f9P/1
  • 听起来您正在查看整场比赛,而不仅仅是捕获第 1 组。

标签: php regex character preg-match


【解决方案1】:
$pat = '=forums/topic/\s*([^/]*)=u';
$str = 'equest lorem ipsum dawhdk scripts. Problem: a href="__;_base_url_j;p_i;oj/index.php?/forums/topic/975-example-maps-to-local-rating/" then does something,';

preg_match($pat, $str, $match);

var_dump($match);

输出:

array(2) {
  [0]=>
  string(45) "forums/topic/975-example-maps-to-local-rating"
  [1]=>
  string(32) "975-example-maps-to-local-rating"
}

【讨论】:

    【解决方案2】:

    您可以像这样使用正则表达式:

    .*/(.*)/
    

    Working demo

    php代码

    $re = '~.*/(.*)/~';
    $str = 'equest lorem ipsum dawhdk scripts. Problem: a href="__;_base_url_j;p_i;oj/index.php?/forums/topic/975-example-maps-to-local-rating/" then does something, ';
    
    preg_match_all($re, $str, $matches);
    
    // Print the entire match result
    var_dump($matches);
    

    【讨论】:

      猜你喜欢
      • 2015-09-04
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多