Php Preg分割,但将分隔符作为一部分
如果我有以下字符串:Php Preg分割,但将分隔符作为一部分,php,Php,如果我有以下字符串: string-with-word-split-should-be-split-here 我想在单词split的最后一次出现时分割字符串,但是这个单词应该是返回结果的一部分-我该怎么做预拆分或分解允许此操作 我期待的结果是: array( 'string-with-word-split-should-be', 'split-here' ); 我可以使用explode,获取我需要的,并使两个阵列内爆等,但似乎我忽略了一个更好的解决方案。是吗?如果preg\u spli
string-with-word-split-should-be-split-here
我想在单词split的最后一次出现时分割字符串,但是这个单词应该是返回结果的一部分-我该怎么做<代码>预拆分或分解允许此操作
我期待的结果是:
array(
'string-with-word-split-should-be', 'split-here'
);
我可以使用explode,获取我需要的,并使两个阵列内爆等,但似乎我忽略了一个更好的解决方案。是吗?如果
preg\u split
工作正常,除了缺少单词split外,您仍然可以在循环中添加它。否则,请使用preg\u match\u all为什么不使用and
以字符串为例,返回值不应该更像
数组('string with word split',-should split','-here')
?如果您使用的是preg_split(),为什么不简单地使用preg_split_DELIM_CAPTURE标志呢?还是我在问题中遗漏了一些深奥的东西?或者如果它包含连字符(如果使用PREG_SPLIT_DELIM_CAPTURE),则可以在分割后使用trim()删除该连字符
<?php
$string = 'string-with-word-split-should-be-split-here';
$splitPosition = strrpos($string, 'split-');
if ($splitPosition !== false) {
$split = array(
trim(substr($string, 0, $splitPosition), '-'),
trim(substr($string, $splitPosition), '-')
);
} else {
$split = array($string);
}
print_r($split);
?>
Array
(
[0] => string-with-word-split-should-be
[1] => split-here
)