在PHP中输出整数之间的文本


Output text between integers in PHP

我有一个文本字符串,我想把它分解成整数之间的多个字符串。

$string = "1 This is the first sentence. 2 This is the second sentence, 3 hello world!";

我想输出到:

$string1 = "1 This is the first sentence.";
$string2 = "2 This is the second sentence,";
$stirng3 = "3 hello world!";

或者数组也可以

这将适用于您的用例,但可能会中断。

preg_match_all("/[0-9]+ [^0-9]+/", $string, $matches);

将给你在$matches

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(30) "1 This is the first sentence. "
    [1]=>
    string(31) "2 This is the second sentence, "
    [2]=>
    string(14) "3 hello world!"
  }
}

您可以使用trim()来去掉多余的空格。


如果您不需要整数

,您也可能对preg_split()感兴趣。
preg_split("/[0-9]+/", $strings);

返回

array(4) {
  [0]=>
  string(0) ""
  [1]=>
  string(29) " This is the first sentence. "
  [2]=>
  string(30) " This is the second sentence, "
  [3]=>
  string(13) " hello world!"
}