通过分隔子字符串将字符串分成两半

问题描述 投票:0回答:4

有以下字符串我需要拆分。

$string = "This is string sample - $2565";
$split_point = " - ";

一: 我需要能够使用正则表达式或任何其他匹配将字符串拆分为两部分,并指定要拆分的位置。

第二: 还想对 $ 进行 preg_match,然后只抓取 $ 右侧的数字。

php string split
4个回答
6
投票
$split_string = explode($split_point, $string);

preg_match('/\$(\d*)/', $split_string[1], $matches);
$amount = $matches[1];

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

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

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

1
投票
$parts = explode ($split_point, $string);
/*
$parts[0] = 'This is string sample'
$parts[1] = '$2565'
*/

1
投票

其他两个答案提到了

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.'

0
投票

explode
是适合您的具体情况的正确解决方案,但是如果您需要分隔符的正则表达式,
preg_split
就是您想要的解决方案

© www.soinside.com 2019 - 2024. All rights reserved.