2015-11-02 20 views
1

我正在嘗試使用REGEX得到來自$str變量的輸入的左右整數。但是我一直不停地把整數和逗號一起取回。我只想要整數而不是逗號。我也嘗試用\d替換通配符.,但仍然沒有解決方案。只有整數的PHP正則表達式

$str = "1,2,3,4,5,6"; 

function pagination() 
{ 
    global $str; 
    // Using number 4 as an input from the string 
    preg_match('/(.{2})(4)(.{2})/', $str, $matches); 
    echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";  
} 

pagination(); 
+1

請寫下您的預期輸出。 – sandeepsure

+0

嘗試'preg_match('/(\ d +),4,(\ d +)/',$ str,$ matches);'then'$ matches [1]'將會有'3'和'$ matches [2]'將持有'5'。 –

+0

爲什麼不使用for循環? 'for($ i = 1; $ i <$ max_pagecount; $ i ++){}' – pmayer

回答

0

我相信你正在尋找非正則表達式捕獲組

這裏就是我所做的:

$regStr = "1,2,3,4,5,6"; 
$regex = "/(\d)(?:,)(4)(?:,)(\d)/"; 

preg_match($regex, $regStr, $results); 
print_r($results); 

給我的結果:

Array ([0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5) 

希望這有助於!

+0

你不需要非捕獲組,只是根本不捕獲','s。 – chris85

0

鑑於你的函數名,我打算假設你需要這個分頁。

下面的解決方案可能會更容易:

$str = "1,2,3,4,5,6,7,8,9,10"; 
$str_parts = explode(',', $str); 

// reset and end return the first and last element of an array respectively 
$start = reset($str_parts); 
$end = end($str_parts); 

這可以防止您的正則不必處理你的號碼進入兩位數。

+0

OP可能需要指定數字兩側的數字。就像在他們的例子中一樣,4.所以返回3和5.不知道雖然... – lintmouse

0

如何使用CSV解析器?

$str = "1,2,3,4,5,6"; 
$line = str_getcsv($str); 
$target = 4; 
foreach($line as $key => $value) { 
if($value == $target) { 
    echo $line[($key-1)] . '<--low high-->' . $line[($key+1)]; 
} 
} 

輸出:

3<--low high-->5 

或一個正則表達式可以是

$str = "1,2,3,4,5,6"; 
preg_match('/(\d+),4,(\d+)/', $str, $matches); 
echo $matches[1]."<--low high->".$matches[2];  

輸出:

3<--low high->5 

這些方法的唯一的缺陷是,如果數字是起始或範圍的結束。情況會是這樣嗎?