【问题标题】:Extract the last characters提取最后一个字符
【发布时间】:2013-02-19 13:38:56
【问题描述】:

我正在尝试提取字符串中的最后两位数字。首先,我删除所有空格或特殊字符并用连字符替换它们,然后如果有两个连字符相互跟随,我将它们删除。 ext 我删除任何尾随连字符。接下来我想提取字符串中 lat 连字符后的最后两个字符。例如,如何提取此字符串中的最后一个字符,即最后一个连字符后的1awesome-page-1。我的代码在这里

$string = 'awesome page@1';
  $slug = preg_replace('/[^a-zA-Z0-9]/', '-', $string);//replace spaces and special characters with space
        $slug = preg_replace('#-{2,}#', '-', $slug);//two hyphens following each other
        $slug = trim($slug, '-');//remove trailing hyphens

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以使用 strrchr() 查找创建的 slug 中的最后一个破折号,然后使用 substr() 跳过该破折号。

    $slug = trim(preg_replace('/[^a-z0-9]+/i', '-', $string), '-');
    
    echo substr(strrchr($slug, '-'), 1);
    

    如果$string 中没有破折号,结果将为空

    Demo

    【讨论】:

      【解决方案2】:

      您可以使用数组作为preg_replace 的参数;

      $str  = 'awesome            page........@1';
      $slug = preg_replace(
          array('~[^a-zA-Z0-9-]~', '~-+~'),
          '-',
          trim($str)
      );
      print $slug; // awesome-page-1
      
      preg_match('~-([^-]*)$~', $slug, $m);
      print $m[1]; // 1
      

      【讨论】:

        【解决方案3】:

        或者,如果您只想匹配连字符后的最后一个字符是数字:

        $slug = trim(preg_replace('/[^a-z0-9]+/i', '-', $string), '-');
        if (preg_match('/^.*-(\d+)$/', $slug, $matches)) {                                                                                               
            echo $matches[1];                                                                
        } else {                                                                             
            echo 'No Match!';                                                                
        }
        

        【讨论】:

          猜你喜欢
          • 2013-03-31
          • 1970-01-01
          • 1970-01-01
          • 2019-05-06
          • 1970-01-01
          • 1970-01-01
          • 2021-10-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多