Preg_match, чтобы поймать точку (.) Более 3 раз - PullRequest
0 голосов
/ 21 мая 2018

Если бы я хотел проверить, имеет ли моя строка 3 или более точек (.), Я бы написал это регулярное выражение

if(preg_match("/^[\.]{3}+$/", $string){
    echo "Match!";

'Потому что обратная косая черта указывает на проверку моей точки, а {3} скажетчисла точек я бы хотел.Было бы довольно просто, если бы это работало.Возможно я что-то здесь упускаю?

Ответы [ 3 ]

0 голосов
/ 21 мая 2018

Вы можете использовать str_replace и вообще не беспокоиться о регулярных выражениях.

str_replace('.', '', 'one.two.three.', $count);
echo $count;

https://3v4l.org/Rl6Se

0 голосов
/ 22 мая 2018

Если говорить прямо, просто попросите php посчитать точки (больше ничего).Это не делает замены, не генерирует массив, не учитывает другие символы.

Код: ( Демо )

$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().

Код: ( Демо )

$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 точки существуют последовательно, вы можете использовать регулярное выражение:

Код: ( Демо )

$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.)
0 голосов
/ 21 мая 2018

только для одного символа из диапазона ascii, вы можете использовать функцию count_chars, которая возвращает массив с номером вхождения для каждого символа:

if ( count_chars($string)[46] > 3 ) {
    ...

46 - десятичное значение для точки.

Обратите внимание: чтобы сделать его более читабельным, вы можете написать:

$char = ord('.');
if ( count_chars($string)[$char] > 3 ) {
    ...
...