[英]Split String into Parts PHP
Have the following string i need to split. 有以下字符串我需要拆分。
$string = "This is string sample - $2565";
$split_point = " - ";
One: I need to be able to split the string into two parts using a regex or any other match and specify where is going to split. 一:我需要能够使用正则表达式或任何其他匹配项将字符串分为两部分,并指定要在哪里进行拆分。
Second: Also want to do a preg_match for $ and then only grab number on the right of $. 第二:也想为$做一个preg_match,然后只抓住$右边的数字。
Any suggestions? 有什么建议么?
$split_string = explode($split_point, $string);
and 和
preg_match('/\$(\d*)/', $split_string[1], $matches);
$amount = $matches[1];
If you want, this could all be done in one regex with: 如果需要,可以使用以下一个正则表达式完成所有操作:
$pattern = '/^(.*)'.preg_quote($split_point).'\$(\d*)$/'
preg_match($pattern, $string, $matches);
$description = $matches[1];
$amount = $matches[2];
$parts = explode ($split_point, $string);
/*
$parts[0] = 'This is string sample'
$parts[1] = '$2565'
*/
Two other answers have mentioned explode()
, but you can also limit the number of parts it's meant to split your source string into. 还有两个答案提到了explode()
,但是您也可以限制将源字符串分割成几个部分的数量。 For instance: 例如:
$s = "This is - my - string.";
list($head, $tail) = explode(' - ', $s, 2);
echo "Head is '$head' and tail is '$tail'\n";
Will given you: 会给你:
Head is 'This is' and tail is 'my - string.'
explode
是适合您特定情况的正确解决方案,但是如果需要分隔符使用正则表达式,则需要preg_split
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.