我想匹配使用正则表达式包含相同变量的添加。
例1
串:
5P + 3P
结果:
5P + 3P
例2
串:
失望+希伯来
结果:
失望+希伯来
例3
串:
失望+玩耍
结果:
失望+玩耍
例4:
串:
5P + 3Q
结果:
没事(根本不匹配)
我在下面创建了自己的正则表达式:
(\d+)(\w+)\+(\d+)(\w+)
但是我的正则表达式不符合上面的最后一个条件。
您可以将正则表达式与其他检查结合使用:
/**
* Checks a given string operation and only returns it if it's valid.
*
* @param string $operation
* @return string|null
*/
function checkOperation(string $operation): ?string
{
// Make sure the operation looks valid (adjust if necessary)
if (!preg_match('/^\d+([a-zA-Z]+)\+\d+([a-zA-Z]+)$/', $operation, $matches)) {
return null;
}
// Make sure the left and right variables have the same characters
if (array_count_values(str_split($matches[1])) != array_count_values(str_split($matches[2]))) {
return null;
}
return $operation;
}
但是:Kua zxsw指出