在整数第一次出现之前提取一段字符串


Extract a piece of string before the first occurance of an integer

我正在开发一个Php脚本。但不幸的是,我在 REGEX 部分真的很差。我想提取这样的东西。

我给出的字符串是:

你好世界! 2016 祝你有美好的一天!

现在,我想将其拆分为一个数组

{"1":"你好世界!","2":"祝你有美好的一天!"}

我想在遇到整数时将其分开。只是,为此我需要一个正则表达式。有人可以帮我解决这个问题吗?另外,请向我推荐一些可以帮助我学习 REGEX 的链接。提前非常感谢你。

最简单的方法是使用 preg_split() 。很明显它的作用(通过正则表达式模式拆分字符串),并且它生成的输出与您的要求非常匹配:

php > $s = "Hello World! 2016 Have a nice day ahead!";
php > $pattern = "/'s+'d+'s+/";
php > $a = preg_split($pattern, $s);
php > print_r($a);
Array
(
    [0] => Hello World!
    [1] => Have a nice day ahead!
)

唯一的区别是您的问题请求基于 1 的索引,而此答案提供基于 0 的索引。您应该更喜欢基于 0 的索引,因为这是 PHP 序列(即数组、字符串等)的默认设置。

提供指向资源的链接超出了 SO 的范围,但是,您可以尝试:

  • http://www.regular-expressions.info/tutorial.html
  • http://regexone.com/
  • http://www.zytrax.com/tech/web/regex.htm

或者通过简单的谷歌搜索可以访问的数十万个其他搜索中的任何一个。


或者,如果您知道分隔字符串的文本值,则可以使用 explode()

php > $s = "Hello World! 2016 Have a nice day ahead!";
php > $delimiter = " 2016 ";
php > $a = explode($delimiter, $s);
php > print_r($a);
Array
(
    [0] => Hello World!
    [1] => Have a nice day ahead!
)

/^(['D]+)'s+'d+'s+(.*)$/应该这样做。

你得到所有非数字,然后是周围有空格的数字,然后是其余的。

把所有的东西放在一起:

$string = 'Hello World! 2016 Have a nice day ahead!';
preg_match('/^(['D]+)'s+'d+'s+(.*)$/', $string, $match);
// $match[1]: Hello World!
// $match[2]: Have a nice day ahead!