2013-01-17 93 views
0

我有一個字符串是這樣的:把數字字符之前斷行字符串中使用PHP

123 qwerty 6 foo bar 55 bar 

我需要像這樣

123 qwerty 
6 foo bar 
55 bar 

如何製作的?

UPD: 我試圖讓它

$subject = "123 qwerty 6 foo 55 bar"; 
$pattern = '/[^0-9]/'; 
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE); 
echo "<pre>"; 
print_r($matches); 

但它沒有爲我工作。

+1

使用pregmatch功能 –

+0

什麼'123 QWERTY 6 FOO 55 bar99x 1 abc'? bar99x會被打破,還是必須在空格後出現號碼? –

+2

[你有什麼嘗試?](http://www.whathaveyoutried.com/)請參閱[FAQ]。 –

回答

3

您可以使用此:

$text = '123 qwerty 6 foo 55 bar baz'; 
$result = preg_replace('/([0-9]+[^0-9]+)/i', '$1\n', $text); 

這看起來至少一個數字後面至少一個字符是不是一個數字並添加換行符。

更多ABOT:

+0

謝謝!正是我需要的。 – user1802209

2

像這樣:

$lineending= "\n"; 
$parts= explode(' ',$string); 
$result= ""; 
for($i=0; $i<count($parts);){ 
    $result .= $parts[$i]; 
    while(!is_numeric($parts[$i]) && $i<count($parts)){ 
     $result .= $parts[$i]; 
     $i+= 1; 
    } 
    $result .= $lineending; 
} 

;-)

+1

是的,你的腳本工作。 但也許不是每行只有一個單詞。 – user1802209

+1

然後你應該編輯你的例子。 –

+0

@OliverA。好的。 – user1802209