目前我在.
处爆炸一个字符串,它可以随心所欲地工作。 唯一的问题是,当.
作为小数点出现时,也会爆炸。有没有办法从分解函数中排除decimal
点?
我目前的设置:如您所见,它在两个数字之间的.
$String = "This is a string.It will split at the previous point and the next one.Here 7.9 is a number";
$NewString = explode('.', $String);
print_r($NewString);
output
Array (
[0] => This is a string
[1] => It will split at the previous point and the next one
[2] => Here 7
[3] => 9 is a number
)
您可以使用preg_split
的正则表达式来/(?<!'d)'.(?!'d)/
:
<?php
$String = "This is a string. It will split at the previous point and the next one. Here 7.9 is a number";
$NewString = preg_split('/(?<!'d)'.(?!'d)/', $String);
print_r($NewString);
?>
输出:
Array
(
[0] => This is a string
[1] => It will split at the previous point and the next one
[2] => Here 7.9 is a number
)
演示
正则表达式是什么意思?
-
(?<!'d)
- 一个"负后看",这意味着它只会在点之前没有数字('d
)时才匹配 -
'.
- 字面.
字符。它需要转义,因为正则表达式中的.
意味着"任何字符" -
(?!'d)
- 一个"负前瞻",意味着它只会在点后没有数字('d
)时才匹配
额外:
您可以通过使用正则表达式作为/(?<!'d)'.(?!'d)'s*/
来摆脱空格,该正则表达式还将匹配点后任意数量的空格,或者您可以使用 $NewString = array_map('trim', $NewString);
.
如果需要像
您的示例一样分解文本,一个简单的方法是分解"."而不是"."。
$String = "This is a string. It will split at the previous point and the next one. Here 7.9 is a number";
$NewString = explode('. ', $String);
print_r($NewString);
output
Array (
[0] => This is a string
[1] => It will split at the previous point and the next one
[2] => Here 7.9 is a number
)