【问题标题】:Extract a substring between two characters in a string PHP提取字符串中两个字符之间的子字符串 PHP
【发布时间】:2013-01-31 06:04:57
【问题描述】:

是否有 PHP 函数可以在字符串中的 2 个不同字符之间提取短语?类似substr();

例子:

$String = "[modid=256]";

$First = "=";
$Second = "]";

$id = substr($string, $First, $Second);

因此$id 将是256

任何帮助将不胜感激:)

【问题讨论】:

  • 您可以分两部分进行:首先从 $first 获取字符串,然后解析结果直到 $second 字符。
  • 您真正想要捕捉什么? id、字符串、=?
  • 在这种情况下,我通常喜欢爆炸我的字符串:explode("=",$String);在第二步中,我可能会通过 rtrim($string, "]"); 摆脱那个“]”

标签: php substr


【解决方案1】:

正则表达式是你的朋友。

preg_match("/=(\d+)\]/", $String, $matches);
var_dump($matches);

这将匹配任何数字,对于其他值,您必须对其进行调整。

【讨论】:

    【解决方案2】:

    使用此代码

    $input = "[modid=256]";
    preg_match('~=(.*?)]~', $input, $output);
    echo $output[1]; // 256
    

    工作示例http://codepad.viper-7.com/0eD2ns

    【讨论】:

    • 对于任何想知道的人:$output 的索引1 包含括号内的模式匹配的文本的原因是$output[0] 是模式匹配的全文。 $output[1] 是第一个子模式匹配的文本; $output[2] 是第二个子模式匹配的文本,以此类推。请参阅the official documentation on preg_match 了解更多信息。
    【解决方案3】:

    你可以使用正则表达式:

    <?php
    $string = "[modid=256][modid=345]";
    preg_match_all("/\[modid=([0-9]+)\]/", $string, $matches);
    
    $modids = $matches[1];
    
    foreach( $modids as $modid )
      echo "$modid\n";
    

    http://eval.in/9913

    【讨论】:

      【解决方案4】:
      $String = "[modid=256]";
      
      $First = "=";
      $Second = "]";
      
      $Firstpos=strpos($String, $First);
      $Secondpos=strpos($String, $Second);
      
      $id = substr($String , $Firstpos, $Secondpos);
      

      【讨论】:

      • substr 的第三个参数是length 不是结束位置。如果你运行它,你会看到$id 等于“=256]”而不是“256”。 php.net/substr
      【解决方案5】:
      $str = "[modid=256]";
      preg_match('/\[modid=(?P<modId>\d+)\]/', $str, $matches);
      
      echo $matches['modId'];
      

      【讨论】:

        【解决方案6】:

        (从评论中移出,因为这里的格式更容易)

        可能是一种懒惰的方法,但在这种情况下,我通常会首先像这样爆炸我的字符串:

        $string_array = explode("=",$String); 
        

        在第二步中,我可能会通过 rtrim 摆脱那个“]”:

        $id = rtrim($string_array[1], "]");
        

        ...但这在结构始终完全相同的情况下才有效...

        -干杯-

        ps:不应该是 $String = "[modid=256]"; 吗?

        【讨论】:

          【解决方案7】:

          试试正则表达式

          $String =" [modid=256]";
          $result=preg_match_all('/(?<=(=))(\d+)/',$String,$matches);
          print_r($matches[0]);
          

          输出

          数组([0] => 256)

          DEMO

          说明 这里它在正则表达式中使用了正则表达式 (?

          【讨论】:

          • 你为什么使用 $result 变量?
          【解决方案8】:

          你可以使用正则表达式,也可以试试这个:

          $String = "[modid=256]";
          
          $First = "=";
          $Second = "]";
          $posFirst = strpos($String, $First); //Only return first match
          $posSecond = strpos($String, $Second); //Only return first match
          
          if($posFirst !== false && $posSecond !== false && $posFirst < $posSecond){
              $id = substr($string, $First, $Second);
          }else{
          //Not match $First or $Second
          }
          

          您应该阅读有关 substr 的内容。最好的方法是使用正则表达式。

          【讨论】:

            【解决方案9】:

            如果您不想使用正则表达式,请使用strstrtrimstrrev 函数:

            // Require PHP 5.3 and higher
            $id = trim(strstr(strstr($String, '='), ']', true), '=]');
            
            // Any PHP version
            $id = trim(strrev(strstr(strrev((strstr($String, '='))), ']')), '=]');
            

            【讨论】:

            • 小心,当$string 中没有=] 时!
            【解决方案10】:

            用途:

            <?php
            
            $str = "[modid=256]";
            $from = "=";
            $to = "]";
            
            echo getStringBetween($str,$from,$to);
            
            function getStringBetween($str,$from,$to)
            {
                $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
                return substr($sub,0,strpos($sub,$to));
            }
            
            ?>
            

            【讨论】:

            • 如果不匹配,函数返回 FALSE。
            【解决方案11】:

            我认为这是获取字符串的方法:

            <?php
            function get_string_between($string, $start, $end){
                $string = ' ' . $string;
                $ini = strpos($string, $start);
                if ($ini == 0) return '';
                $ini += strlen($start);
                $len = strpos($string, $end, $ini) - $ini;
                return substr($string, $ini, $len);
            }
            
            
            $fullstring = '.layout { 
            
            color: {{ base_color }} 
            
            }
            
            li { 
            
            color: {{ sub_color }} 
            
            } 
            
            .text { 
            
            color: {{ txt_color }}
            
             }
            
             .btn { 
            
            color: {{ btn_color }}
            
             }
            
            .more_text{
            
            color:{{more_color}}
            
            }';
            
              $parsed = get_string_between($fullstring, '{{', '}}');
              echo $parsed;
            ?>
            

            【讨论】:

              猜你喜欢
              • 2013-12-11
              • 1970-01-01
              • 2013-09-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多