我有一个小问题需要排序。我想要删除字符串的一部分或拆分它。
我最后想做的是把它分成两个变量其中有"One, Two, Three"answers"1,2,3";,我不确定我是否可以把它分成两部分,或者我是否必须删除"-"然后再做一遍,去掉";-"最后得到两个变量。无论如何,我已经看了一下,似乎preg_split()
或preg_match()
可能工作,但不知道preg
模式。
这是我目前为止写的:
$string = 'One-1, Two-2, Three-3';
$pattern = '????????????';
preg_match_all($pattern, $string, $matches);
print_r($matches);
编辑:对不起,我的问题写错了:
基本上,如果有人可以帮助我与preg
模式拆分值,所以我有一个数组,一二三和1,2,3
---------------- 编辑 --------------
我有另一个问题,如果我有这个,preg_match会如何改变:
One Object-1, Two Object-2
现在我在"-"前面有不止一个单词其中想要存储在一起的"1"它自己?
试试这个:
$string = 'One-1, Two-2, Three-3';
$pattern = '/(?P<first>'w+)-(?P<second>'w+)/';
preg_match_all($pattern, $string, $matches);
print_r($matches['first']);
print_r($matches['second']);
输出:Array ( [0] => One [1] => Two [2] => Three )
Array ( [0] => 1 [1] => 2 [2] => 3 )
如果总是用"-"代替
$string = "One-1";
$args = explode("-", $string);
// $args[0] would have One
// $args[1] would have 1
您可以在这里阅读有关此函数的更多信息:http://php.net/manual/en/function.explode.php
应该可以:
[^-]+
但是为什么要使用regexp呢?你可以直接使用"-"