Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将字符串拆分为多个部分_Php_Regex_String - Fatal编程技术网

Php 将字符串拆分为多个部分

Php 将字符串拆分为多个部分,php,regex,string,Php,Regex,String,我需要拆分以下字符串 $string = "This is string sample - $2565"; $split_point = " - "; 一: 我需要能够使用正则表达式或任何其他匹配项将字符串拆分为两部分,并指定要拆分的位置 $string = "This is string sample - $2565"; $split_point = " - "; 第二: 还想为$进行预匹配,然后只获取$右侧的数字 有什么建议吗 $split_string = explode($split

我需要拆分以下字符串

$string = "This is string sample - $2565";
$split_point = " - ";
一: 我需要能够使用正则表达式或任何其他匹配项将字符串拆分为两部分,并指定要拆分的位置

$string = "This is string sample - $2565";
$split_point = " - ";
第二: 还想为$进行预匹配,然后只获取$右侧的数字

有什么建议吗

$split_string = explode($split_point, $string);

如果您愿意,可以在一个正则表达式中完成这一切,其中包括:

$pattern = '/^(.*)'.preg_quote($split_point).'\$(\d*)$/'

preg_match($pattern, $string, $matches);
$description = $matches[1];
$amount = $matches[2];

如果您愿意,可以在一个正则表达式中完成这一切,其中包括:

$pattern = '/^(.*)'.preg_quote($split_point).'\$(\d*)$/'

preg_match($pattern, $string, $matches);
$description = $matches[1];
$amount = $matches[2];

另外两个答案提到了
explode()
,但是您也可以限制将源字符串拆分成的部分的数量。例如:

$s = "This is - my - string.";
list($head, $tail) = explode(' - ', $s, 2);
echo "Head is '$head' and tail is '$tail'\n";
将向您提供:

Head is 'This is' and tail is 'my - string.'

另外两个答案提到了
explode()
,但是您也可以限制将源字符串拆分成的部分的数量。例如:

$s = "This is - my - string.";
list($head, $tail) = explode(' - ', $s, 2);
echo "Head is '$head' and tail is '$tail'\n";
将向您提供:

Head is 'This is' and tail is 'my - string.'

explode
是您特定情况下的正确解决方案,但是如果您需要分隔符的正则表达式,则
preg_split
是您想要的解决方案,但是,
preg_split
是您想要的,如果您需要分隔符的正则表达式

请,为避免意外错误,请在regex示例中的$split_点周围添加preg_引号。请,为避免意外错误,在正则表达式示例中,在$split_点周围添加preg_引号。输出不是:Head是'This is-',tail是'my-string'。不,绝对不是。在发布之前,我甚至在PHP REPL中检查了它。那么,第一个-?你完全正确。我忘了你爆炸了“-”而不是“-”。我将如何从最后一个而不是第一个分裂出去。我可以从右到左进行分解搜索吗?输出不是吗:头是“这是-”,尾是“我的字符串”?不,绝对不是。在发布之前,我甚至在PHP REPL中检查了它。那么,第一个-?你完全正确。我忘了你爆炸了“-”而不是“-”。我将如何从最后一个而不是第一个分裂出去。我可以改为从右到左进行分解搜索吗?当您只提供一个示例字符串时,很难知道输入字符串的变化情况。您是否希望
这是字符串示例
2565
作为输出数组中的两个元素?当您只提供一个示例字符串时,很难知道输入字符串可能会有什么变化。您是否希望
这是字符串sample
2565
作为输出数组中的两个元素?