【问题标题】:Get vector of string between strings (Php)获取字符串之间的字符串向量(Php)
【发布时间】:2014-02-18 22:38:54
【问题描述】:

我已经尝试了几个小时来获取由"{i}""{[i]}" 分隔的字符串,例如{i}Esse{[i]},其中i 是一个整数。基于 get string between 2 strings。我不知道发生了什么,所以我决定寻求帮助。

我的代码是这样的:

<?php
include "keepGetInBetweenStrings.php";

$x['city1']='Esse';
$x['city2']='';
$x['city3']='é';
$x['city4']='um bom exemplo de';
$x['city5']=' uma portuguese-string!!';

$allCities='';
$cont=0;

for($i=1;$i<=5;$i++){
    if($x['city'."$i"]!=''){
        $cont=$cont+1;
       $allCities=$allCities.'{'."$cont".'}'.$x['city'."$i"].'{['."$cont".']}'; 
    }
}
       echo $allCities;

       echo "<br>";


for($i=1;$i<=5;$i++){
    $token=getInbetweenStrings('{'."$i".'}', '{['."$i".']}', $allCities);

    echo $token."<br>";
}       


?>

<?php

function getInBetweenStrings($start, $end, $str){
    echo $start."<br>";
    echo $end."<br>";
    $matches = array();
    $regex = "/$start(.*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[0];
}
?>

非常感谢任何帮助。

输出是

 {1}Esse{[1]}{2}é{[2]}{3}um bom exemplo de{[3]}{4} uma portuguese-string!!{[4]}

{1}
{[1]}

{2}
{[2]}

{3}
{[3]}

{4}
{[4]}

{5}
{[5]}

pHP 日志错误是

[2014 年 1 月 27 日星期一 19:08:20.406027] [:error] [pid 2638] [client 127.0.0.1:50728] PHP 警告:preg_match_all():编译失败:在 /var/ 中的偏移量 2 处没有可重复的内容第 8 行 www/NetBeansProjects/NewPhpProject/keepGetInBetweenStrings.php [Mon Jan 27 19:08:20.406039 2014] [:error] [pid 2638] [client 127.0.0.1:50728] PHP 注意:未定义的偏移量:/var/www/NetBeansProjects/NewPhpProject/keepGetInBetweenStrings.php 第 9 行中的 0

【问题讨论】:

    标签: php regex string


    【解决方案1】:

    {...} 在正则表达式中有特殊含义。您从另一个问题复制的 getInbetweenStrings 函数假定分隔符字符串不包含任何特殊的正则表达式字符。您需要使用preg_quote 转义字符以解决此问题。

    【讨论】:

      【解决方案2】:

      请记住,{x}(其中 x 是整数)是正则表达式中的重复运算符。例如

      /foo{7}/
      

      将匹配

      foooooooo
        1234567
      

      f,一个o,然后是另外7个oo{7})。

      换句话说,您实际上是将正则表达式元字符插入到正则表达式中,但不希望它们被视为正则表达式 - 这意味着您正遭受相当于 SQL 注入攻击的正则表达式。

      你需要先preg_quote你的值,它会转义那些元字符,并给你更多类似的东西

      /foo\{7\}/ instead.
      

      所以...

      function getInBetweenStrings($start, $end, $str){
           $regex = '/' . preg_quote($start) . '(.*)' . preg_quote($end) . '/';
           etc...
      }
      

      【讨论】:

        猜你喜欢
        • 2013-09-12
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多