Web

Функции startWith() и endWith() в PHP

Как я могу написать две функции, которые будут принимать строку и возвращать результат, если они начинаются с указанного символа/строки или заканчивается другим символом?

Например:

$str = '|apples}';

echo startsWith($str, '|'); // Возвращает true

echo endsWith($str, '}');   // Возвращает true

 

Ответ 1

function startsWith( $haystack, $needle ) {

     $length = strlen( $needle );

     return substr( $haystack, 0, $length ) === $needle;

}

 

function endsWith( $haystack, $needle ) {

    $length = strlen( $needle );

    if( !$length ) {

        return true;

    }

    return substr( $haystack, -$length ) === $needle;

}

Используйте этот код, если вам не надо использовать регулярное выражение.

 

Ответ 2

Можно использовать функцию substr_compare, чтобы проверить начало и конец строки:

function startsWith($haystack, $needle) {

    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;

}

function endsWith($haystack, $needle) {

    return substr_compare($haystack, $needle, -strlen($needle)) === 0;

}

 

Ответ 3

Есть следующие функции:

function substr_startswith($haystack, $needle) {

    return substr($haystack, 0, strlen($needle)) === $needle;

}

 function preg_match_startswith($haystack, $needle) {

    return preg_match('~' . preg_quote($needle, '~') . '~A', $haystack) > 0;

}

function substr_compare_startswith($haystack, $needle) {

    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;

}

 function strpos_startswith($haystack, $needle) {

    return strpos($haystack, $needle) === 0;

}

 function strncmp_startswith($haystack, $needle) {

    return strncmp($haystack, $needle, strlen($needle)) === 0;

}

 function strncmp_startswith2($haystack, $needle) {

    return $haystack[0] === $needle[0]

        ? strncmp($haystack, $needle, strlen($needle)) === 0

        : false;

}

Использование этих функций:

echo 'generating tests';

for($i = 0; $i < 100000; ++$i) {

    if($i % 2500 === 0) echo '.';

    $test_cases[] = [

        random_bytes(random_int(1, 7000)),

        random_bytes(random_int(1, 3000)),

    ];

}

echo "done!\n";

$functions = ['substr_startswith', 'preg_match_startswith', 'substr_compare_startswith', 'strpos_startswith', 'strncmp_startswith', 'strncmp_startswith2'];

$results = [];

foreach($functions as $func) {

    $start = microtime(true);

    foreach($test_cases as $tc) {

        $func(...$tc);

    }

    $results[$func] = (microtime(true) - $start) * 1000;

}

asort($results);

foreach($results as $func => $time) {

    echo "$func: " . number_format($time, 1) . " ms\n";

}

Результат для (PHP 7.0.9)

(Отсортировано от самого быстрого к самому медленному)

strncmp_startswith2: 40.2 ms

strncmp_startswith: 42.9 ms

substr_compare_startswith: 44.5 ms

substr_startswith: 48.4 ms

strpos_startswith: 138.7 ms

preg_match_startswith: 13,152.4 ms

Результат для (PHP 5.3.29)

(Отсортировано от самого быстрого к самому медленному)

strncmp_startswith2: 477.9 ms

strpos_startswith: 522.1 ms

strncmp_startswith: 617.1 ms

substr_compare_startswith: 706.7 ms

substr_startswith: 756.8 ms

preg_match_startswith: 10,200.0 ms

 

Ответ 4

Есть простое решение, которое предполагает strlen calculationsstring allocations (substr). Использование функций 'strpos' и 'stripos', которые возвращают индекс первого вхождения $needle в $haystack:

function startsWith($haystack,$needle,$case=true) {

    if ($case)

        return strpos($haystack, $needle, 0) === 0;

    return stripos($haystack, $needle, 0) === 0;

}

 function endsWith($haystack,$needle,$case=true) {

    $expectedPosition = strlen($haystack) - strlen($needle);

    if ($case)

        return strrpos($haystack, $needle, 0) === $expectedPosition;

    return strripos($haystack, $needle, 0) === $expectedPosition;

}

 

Схожие статьи

Как создать свой поисковик и возможно ли это сделать самостоятельно?
Web

Как создать свой поисковик и возможно ли это сделать самостоятельно?

Web

Как удалить index.php из пути codeigniter

Web

Как предотвратить SQL-инъекцию в PHP?

Кто такой веб-разработчик. Описание профессии и ее подводные камни
Web

Кто такой веб-разработчик. Описание профессии и ее подводные камни

×