php preg_match 具有多种模式

php preg_match with multiple patterns

我有两个模式,我想在一个字符串中搜索它们。 他们是这样的:

$pattern = '/,3$/'
$pattern = '/^1,/';

实际上我想找到以 <code>1, 开头或以 <code>,3[=16 结尾的字符串=]

我的字符串格式如下:

a => 1,2
b => 31,2
c => 4,3

例如a和c匹配!
我如何使用 preg_match 来检查这个模式?
坦克寻求帮助。

这样试试

preg_match("/^1,|,3$/", $string)

/(^1,)|(,3$)/ 应该适合你。

以防万一有一天您需要非正则表达式的解决方案,您可以使用以下 startswith and endswith functions:

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";

IDEONE demo 的输出:

True1
True3