0

次のような文字列があります。

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);

しかし、それは私にとってはうまくいきません。

4

3 に答える 3

3

これを使用できます:

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

これは、少なくとも 1 つの数字の後に、数字ではない少なくとも 1 つの文字が続くものを探し、改行を追加します。

続きを読む:

于 2013-01-17T14:25:49.850 に答える
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; 
 }

;-)

于 2013-01-17T14:06:03.463 に答える
0

これを試して:

$subject = '123 qwerty 6 foo 55 bar';
$pattern = '/ (?=[\d]+)/';
$replacement = "\n";

$result = preg_replace( $pattern, $replacement, $subject );

print_r( $result );

プロデュース:

123 qwerty
6 foo
55 bar

PHP デモ: http://codepad.org/MNLgaySd


その鍵は正規表現の「正先読み」にあり、(?=...)

正規表現のデモ: http://rubular.com/r/i4CdoEL9f4

于 2013-01-17T14:31:47.687 に答える