我有两种模式,我想在一个字符串中搜索它们。 他们是这样的:php preg_match与多种模式
$pattern = '/,3$/'
$pattern = '/^1,/';
其实我想找到与
开始字符串或与1,
,3
我的琴弦都是这种格式结尾:
a => 1,2
b => 31,2
c => 4,3
例如和c是匹配!
我该如何使用preg_match来检查这种模式?
坦克的帮助。
我有两种模式,我想在一个字符串中搜索它们。 他们是这样的:php preg_match与多种模式
$pattern = '/,3$/'
$pattern = '/^1,/';
其实我想找到与
开始字符串或与1,
,3
我的琴弦都是这种格式结尾:
a => 1,2
b => 31,2
c => 4,3
例如和c是匹配!
我该如何使用preg_match来检查这种模式?
坦克的帮助。
尝试这种方式
preg_match("/^1,|,3$/", $string)
/(^1,)|(,3$)/
应该为你工作。
万一有一天你会需要一个非正则表达式的解决方案,你可以使用以下startswith and endswith functions:在IDEONE demo的
function startsWith($haystack, $needle) {
// search backwards starting from haystack length characters from the end
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
function endsWith($haystack, $needle) {
// search forward starting from end minus needle length characters
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}
if (startsWith("1,2", "1,") || endsWith("1,2", ",3"))
echo "True1". "\n";
if (startsWith("31,2", "1,") || endsWith("31,2",",3"))
echo "True2". "\n";
if (startsWith("4,3", "1,") || endsWith("4,3",",3"))
echo "True3" . "\n";
输出:
True1
True3
遍历它们和与之相匹配。 –
我正在寻找只有一个支票的方式......! –
你需要匹配什么?你是否需要检查字符串是以1开头还是以3结尾,还是需要提取所有不是这样的内容?如果你只需要匹配,只需使用或运算符'|'。否则,如果你需要匹配其余的,像这样的东西会工作:'(?=^1,(。*?)$)|(?=(。*?),3 $)' – briosheje