【问题标题】:preg_replace: all after first "-"preg_replace:都在第一个“-”之后
【发布时间】:2016-08-19 01:09:11
【问题描述】:

我有:

$text = "1235-text1-text2-a1-780-c-text3";

如何使用 preg_replace 获得这个?需要重定向301。

"text1-text2-a1-780-c-text3"

【问题讨论】:

  • 你得到了替换前的例子。
  • trim(strstr($text, '-'), '-');
  • 请努力提出一个好的和明确的问题。
  • 你是放弃了还是怎么了?

标签: php regex replace preg-replace


【解决方案1】:

如你所愿,使用 preg_replace:

$re = '/^([\w]*-)/';
$str = "1235-text1-text2-a1-780-c-text3";
$match = preg_replace($re, "", $str);
var_dump($match);

使用 preg_match 的替代方法:

$re = '/-(.*)/';
$str = "1235-text1-text2-a1-780-c-text3";
preg_match($re,$str,$matches);

var_dump($matches[1]);

【讨论】:

    【解决方案2】:

    或者使用 preg_match

    <?php
    $text = "1235-text1-text2-a1-780-c-text3";
    
    preg_match("%[^-]*-(.*)%",$text, $matchs);
    var_dump($matchs[1]);
    // Output "text1-text2-a1-780-c-text3"
    ?>
    

    【讨论】:

      【解决方案3】:

      这会起作用

      [^-]*-
      

      Regex Demo

      PHP 代码

      $re = "/[^-]*-/"; 
      $text = "1235-text1-text2-a1-780-c-text3"; 
      $result = preg_replace($re, "", $text, 1);
      

      Ideone Demo

      【讨论】:

        【解决方案4】:

        不需要正则表达式:

        $result = substr($text, strpos($text, '-')+1);
        

        或者:

        $result = trim(strstr($text, '-'), '-'); 
        

        【讨论】:

          【解决方案5】:

          没用的正则表达式可以试试

          trim(strstr($text, '-'),'-');
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-10-27
            • 1970-01-01
            • 2022-01-20
            • 1970-01-01
            相关资源
            最近更新 更多