2014-01-27 152 views
0

我一直在嘗試幾個小時才能得到由"{i}""{[i]}"分隔的字符串,如{i}Esse{[i]},其中i是一個整數。基於 get string between 2 strings。我不知道它發生了什麼,所以我決定尋求幫助。獲取字符串之間的字符串向量(Php)

我的代碼是這樣的:

<?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的日誌錯誤是

[週一19年1月27日:08:20.406027 2014] [:錯誤] [PID 2638] [客戶端127.0.0.1: 50728] PHP警告:preg_match_all():編譯失敗:無法在第8行的/var/www/NetBeansProjects/NewPhpProject/keepGetInBetweenStrings.php的偏移量2處重複執行 [Mon Jan 27 19:08:20.406039 2014] [:error] [pid 2638] [client 127.0.0.1:50728] PHP注意:在/ var/www/NetBeansProjects/NewPhpProject/keepGetInBetweenStrings中未定義偏移量:0。 php on line 9

回答

3

請記住{x}(其中x是一個整數)是正則表達式中的重複運算符。例如。

/foo{7}/ 

將匹配

foooooooo 
    1234567 

f,一個o,接着7更o「S(o{7})。

換句話說,你是從字面上將正則表達式元字符插入到正則表達式中,但不希望它們被當作正則表達式 - 這意味着你正在遭受SQL注入攻擊的正則表達式的等價物。

您需要首先preg_quote你的價值觀,其逃生者的元字符,給你更喜歡

/foo\{7\}/ instead. 

所以什麼......

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

{...}在正則表達式的特殊含義。從另一個問題中複製的getInbetweenStrings函數假定分隔符字符串不包含任何特殊的正則表達式字符。您需要使用preg_quote轉義字符才能解決此問題。

相關問題