如果我想验证我的字符串是否有3个或更多点(。)我会写这个正则表达式
if(preg_match("/^[\.]{3}+$/", $string){
echo "Match!";
'因为反斜杠表示验证我的点,而{3}会说我想要的数字。如果有效的话会很简单。也许我在这里错过了什么?
答案 0 :(得分:4)
对于ascii范围中只有一个字符,您可以使用count_chars函数返回一个数组,其中包含每个字符的出现次数:
if ( count_chars($string)[46] > 3 ) {
...
46是点的十进制值。
请注意,为了使其更具可读性,您可以写:
$char = ord('.');
if ( count_chars($string)[$char] > 3 ) {
...
答案 1 :(得分:2)
最直接,只要求php计算点数(仅此而已)。这不会替换,它不会生成数组,也不会计算任何其他字符。
代码:(Demo)
$strings = ['This is. a. test.',
'This is a. test.',
'This is. a test',
'This is a test',
'This. is. a. test.'
];
foreach ($strings as $string) {
if (($dots = substr_count($string, '.')) >= 3) { // assign count as variable and make comparison
echo "Yes, 3 or more dots ($string -> $dots)";
} else {
echo "Nope, less than 3 dots ($string -> $dots)";
}
echo "\n";
}
输出:
Yes, 3 or more dots (This is. a. test. -> 3)
Nope, less than 3 dots (This is a. test. -> 2)
Nope, less than 3 dots (This is. a test -> 1)
Nope, less than 3 dots (This is a test -> 0)
Yes, 3 or more dots (This. is. a. test. -> 4)
如果要检查连续是否有3个,请使用strpos()
。
代码:(Demo)
$strings = ['This is. a. test.',
'This is a........... test.',
'This is. a test',
'This is a test',
'This. is... a. test.'
];
foreach ($strings as $string) {
if (($offset = strpos($string, '...')) !== false) {
echo "Yes, found 3 in a row ($string -> $offset)";
} else {
echo "Nope, no occurrence of 3 dots in a row ($string)";
}
echo "\n";
}
输出:
Nope, no occurrence of 3 dots in a row (This is. a. test.)
Yes, found 3 in a row (This is a........... test. -> 9)
Nope, no occurrence of 3 dots in a row (This is. a test)
Nope, no occurrence of 3 dots in a row (This is a test)
Yes, found 3 in a row (This. is... a. test. -> 8)
如果要指定连续存在3个点,可以使用正则表达式:
代码:(Demo)
$strings = ['This is. a.. test...',
'This is a........... test.',
'...This is. a.. ..test',
'This is a test',
'This. is... a. test.'
];
foreach ($strings as $string) {
if (preg_match('~(?<!\.)\.{3}(?!\.)~', $string)) {
echo "Yes, found an occurrence of not more than 3 dots in a row ($string)";
} else {
echo "Nope, no occurrence of exactly 3 dots in a row ($string)";
}
echo "\n";
}
输出:
Yes, found an occurrence of not more than 3 dots in a row (This is. a.. test...)
Nope, no occurrence of exactly 3 dots in a row (This is a........... test.)
Yes, found an occurrence of not more than 3 dots in a row (...This is. a.. ..test)
Nope, no occurrence of exactly 3 dots in a row (This is a test)
Yes, found an occurrence of not more than 3 dots in a row (This. is... a. test.)
答案 2 :(得分:1)
您可以使用str_replace
,而不必担心正则表达式。
str_replace('.', '', 'one.two.three.', $count);
echo $count;