어떻게 이렇게 될 경우 다시 두 가지 기능을 쓰기 시작하여 문자열으로 시행하십시오 특정 문자 / 문자열 또는 motor1.1end 그걸로?
예를 들면 다음과 같습니다.
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
function endsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
이 경우, don& # 39 regex 사용하지 않는다.
'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;
}
php 7 에서, 이 중 가장 빠른 솔루션뀉뀉뀉뀉 < sup> 합니다. (벤치마트 스크립트입니다). 건초 더미, 전체 길이 없고, 부분 및 다양한 바늘을 어하여 테스트되었습니다 8KB 해당되어서는 건이다. '터치' 가 더 있지만, /sup> 스테른시모프 시작됩니다. ends-with.< 확인할 수 없습니다.
2016년 23 일 업데이트되도록
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";
}
(빠른) 를 정렬할지 최저속)
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
(빠른) 를 정렬할지 최저속)
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
[startswith_benchmark.php] (https://gist.github.com/mnpenner/9a941ab830a457ed0358 # file-startswith_benchmark-php)
지금까지 모든 대답을 해야 할 것 같다 ',', '불필요한 작동합니까 로드되는지 스트린 계산이므로 구체화하십시오 할당 (substr)' 등. # 39, & # 39, & # 39 는 strpos& ',' 와 ',' 기능을 stripos& # 39 반품해야 색인입니다 처음 나타나는 '$ $ 짚단' 바늘 '에서':
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;
}
function startsWith($haystack, $needle, $case = true) {
if ($case) {
return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}
return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}
function endsWith($haystack, $needle, $case = true) {
if ($case) {
return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}
return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}
정규 표현식 기능을 갖추고 있지만, 그 위에 다른 tweak 위에서 제시한 적도 있다.
function startsWith($needle, $haystack) {
return preg_match('/^' . preg_quote($needle, '/') . '/', $haystack);
}
function endsWith($needle, $haystack) {
return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
}
이 질문에 답을 한 자리 잡을 수 있지만, 이미 많은 것보다 간단해진다는 모두야 경우도 있습니다.
preg_match('/^ABC/', $myString); // "^" here means beginning of string
preg_match('/ABC$/', $myString); // "$" here means end of string
내가 원하는 건 내 여부를 확인할 수 있는 간단한 경우 motor1.1end 문자열으로 슬래시 (slash):
preg_match('#/$#', $myPath); // Use "#" as delimiter instead of escaping slash
장점: # 39, 이후 아주 짧고 간단한 it& don& # 39, 함수를 정의하는 데 없는 경우 (예: ' ()' 엔즈비트) 위 그림 참조).
하지만, 이 모든 사건의 솔루션입니다 - 아닙니다 그냥 매우 특수한 경우다.
이 경우, 속도는 시도하시겠습니까 합니다. (I believe it 는 가장 빠른 방법)
단 1 개의 문자 $ 짚단 아웃하기로 문장열 사용할 수 있습니다
function startsWithChar($needle, $haystack)
{
return ($needle[0] === $haystack);
}
function endsWithChar($needle, $haystack)
{
return ($needle[strlen($needle) - 1] === $haystack);
}
$str='|apples}';
echo startsWithChar($str,'|'); //Returns true
echo endsWithChar($str,'}'); //Returns true
echo startsWithChar($str,'='); //Returns false
echo endsWithChar($str,'#'); //Returns false
여기서 두 가지 기능을 갖춘 don& 때 유용할 수 있는 문자열 t # 39, 임시 소개하십시오 상당히 큰 바늘을 있다.
function startsWith($haystack, $needle)
{
return strncmp($haystack, $needle, strlen($needle)) === 0;
}
function endsWith($haystack, $needle)
{
return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
지금까지 내가 다 알고 있지만, 보면 볼 수 있습니다. 스테른시모프 도왔으매 비교할 수 있기 때문에 문자열 길이를 설정할 수 있습니다.
function startsWith($haystack, $needle, $case=true) {
if ($case)
return strncasecmp($haystack, $needle, strlen($needle)) == 0;
else
return strncmp($haystack, $needle, strlen($needle)) == 0;
}
# Checks if a string ends in a string
function endsWith($haystack, $needle) {
return substr($haystack,-strlen($needle))===$needle;
}
# This answer
function endsWith($haystack, $needle) {
return substr($haystack,-strlen($needle))===$needle;
}
# Accepted answer
function endsWith2($haystack, $needle) {
$length = strlen($needle);
return $length === 0 ||
(substr($haystack, -$length) === $needle);
}
# Second most-voted answer
function endsWith3($haystack, $needle) {
// search forward starting from end minus needle length characters
if ($needle === '') {
return true;
}
$diff = \strlen($haystack) - \strlen($needle);
return $diff >= 0 && strpos($haystack, $needle, $diff) !== false;
}
# Regex answer
function endsWith4($haystack, $needle) {
return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
}
function timedebug() {
$test = 10000000;
$time1 = microtime(true);
for ($i=0; $i < $test; $i++) {
$tmp = endsWith('TestShortcode', 'Shortcode');
}
$time2 = microtime(true);
$result1 = $time2 - $time1;
for ($i=0; $i < $test; $i++) {
$tmp = endsWith2('TestShortcode', 'Shortcode');
}
$time3 = microtime(true);
$result2 = $time3 - $time2;
for ($i=0; $i < $test; $i++) {
$tmp = endsWith3('TestShortcode', 'Shortcode');
}
$time4 = microtime(true);
$result3 = $time4 - $time3;
for ($i=0; $i < $test; $i++) {
$tmp = endsWith4('TestShortcode', 'Shortcode');
}
$time5 = microtime(true);
$result4 = $time5 - $time4;
echo $test.'x endsWith: '.$result1.' seconds # This answer<br>';
echo $test.'x endsWith2: '.$result4.' seconds # Accepted answer<br>';
echo $test.'x endsWith3: '.$result2.' seconds # Second most voted answer<br>';
echo $test.'x endsWith4: '.$result3.' seconds # Regex answer<br>';
exit;
}
timedebug();
10000000x endsWith: 1.5760900974274 seconds # This answer
10000000x endsWith2: 3.7102129459381 seconds # Accepted answer
10000000x endsWith3: 1.8731069564819 seconds # Second most voted answer
10000000x endsWith4: 2.1521229743958 seconds # Regex answer
[ 스트라포스 '' ) 사용할 수 있습니다 (http://php.net/manual/en/function.strpos.php) 및 [ 스테르포스 ''] (http://php.net/manual/en/function.strrpos.php)
$bStartsWith = strpos($sHaystack, $sNeedle) == 0;
$bEndsWith = strrpos($sHaystack, $sNeedle) == strlen($sHaystack)-strlen($sNeedle);
S # 39, here& 멀티바이트 안전하다구요 버전의 수락됨 오토메이티드 작동하잖아 과태료를, UTF-8 문장열:
function startsWith($haystack, $needle)
{
$length = mb_strlen($needle, 'UTF-8');
return (mb_substr($haystack, 0, $length, 'UTF-8') === $needle);
}
function endsWith($haystack, $needle)
{
$length = mb_strlen($needle, 'UTF-8');
return $length === 0 ||
(mb_substr($haystack, -$length, $length, 'UTF-8') === $needle);
}
스테이츠비트 초점을 맞추고 있는지 문장열 경우 비어 있지 않으면, 그 전에 먼저 챨 비교 시험을 추가에는 스트린 등, 속도용으로 창조하셨노 약간 위로:
function startswith5b($haystack, $needle) {
return ($haystack{0}==$needle{0})?strncmp($haystack, $needle, strlen($needle)) === 0:FALSE;
}
이는 짐작이지만요. (20% - 30%) 가속화합니다. 추가 테스트, {1} {1} = $ $ 짚단 바늘 같은 다른 챨 않는 듯 하다 셨으며 속도 향상을 크게 둔화될 수도 있습니다.
'=' 보다 '=' 될 것 같다. 조건부 작동자 ' (a)' 보다 ' (a) b, c / b 경우 것 같다. 다른 캜. '
이 작업에 대한 올바른 도구 스트라포스 는 빠르고 아니다.
이해하기 조금 슬라이드에서는 배빠르게 표시됨과 예:
Search a12345678c inside bcdefga12345678xbbbbb.....bbbbba12345678c
With strccmp, etc...
is a===b? NO
return false
With strpos
is a===b? NO -- iterating in haysack
is a===c? NO
is a===d? NO
....
is a===g? NO
is a===g? NO
is a===a? YES
is 1===1? YES -- iterating in needle
is 2===3? YES
is 4===4? YES
....
is 8===8? YES
is c===x? NO: oh God,
is a===1? NO -- iterating in haysack again
is a===2? NO
is a===3? NO
is a===4? NO
....
is a===x? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
...
... may many times...
...
is a===b? NO
is a===a? YES -- iterating in needle again
is 1===1? YES
is 2===3? YES
is 4===4? YES
is 8===8? YES
is c===c? YES YES YES I have found the same string! yay!
was it at position 0? NOPE
What you mean NO? So the string I found is useless? YEs.
Damn.
return false
스트린 언약보다는 가정할 경우 전체 문자열 (그보다 이 경우) 는 편리한 전혀 아니다.
또한 단순한 아래 오토메이티드 효율형 수 있길 바란다.
$content = "The main string to search";
$search = "T";
//For compare the begining string with case insensitive.
if(stripos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the begining string with case sensitive.
if(strpos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case insensitive.
if(stripos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case sensitive.
if(strpos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
이 답변 에서 음펜 을 가지고 있지만, 매우 중요하고 큰 제공된 벤치마트 죄송합니다. 믿기지 않을 정도로 철저한 감독.
이 때문에 모든 바이트입니다 다를 수 있는 가능성을 완벽하게 무순서적으로 바늘을 및 건초 더미 바늘 짚단 페어당 바이트입니다 99.609375% 가 맨 처음 있는 일, 즉, 평균적으로 99609 차이가 날 것이라고 100000 쌍 중 맨 처음 바이트입니다. 즉, '는' 구축을 위한 첫 번째 바이트입니다 스테이츠비트 벤치마트 크게 바이어스됨 명시적으로 어떤 체크 등 '에서' strncmp_startswith2.
대신 테스트 생성 경우 루프가 구축됩니까 다음과 같습니다.
echo 'generating tests';
for($i = 0; $i < 100000; ++$i) {
if($i % 2500 === 0) echo '.';
$haystack_length = random_int(1, 7000);
$haystack = random_bytes($haystack_length);
$needle_length = random_int(1, 3000);
$overlap_length = min(random_int(0, $needle_length), $haystack_length);
$needle = ($needle_length > $overlap_length) ?
substr($haystack, 0, $overlap_length) . random_bytes($needle_length - $overlap_length) :
substr($haystack, 0, $needle_length);
$test_cases[] = [$haystack, $needle];
}
echo " done!<br />";
벤치마크 결과를 떠날려하면 약간 다르다.
strncmp_startswith: 223.0 ms
substr_startswith: 228.0 ms
substr_compare_startswith: 238.0 ms
strncmp_startswith2: 253.0 ms
strpos_startswith: 349.0 ms
preg_match_startswith: 20,828.7 ms
물론 이 벤치마트 않을 수는 있지만 부분적으로 일치하는 알고리즘 효율성을 테스트를 완벽하게 색채가 없는 분들이 맡도록 지정하면 바늘을 잘 알려져 있다.
난 보통 끝날 것 같은 라이브러리를 사용하여 [밑줄 php] (http://anahkiasen.github.io/underscore-php/ # 구체화하십시오 엔즈비트) 요즘.
<! - 언어: php - >.
require_once("vendor/autoload.php"); //use if needed
use Underscore\Types\String;
$str = "there is a string";
echo( String::startsWith($str, 'the') ); // 1
echo( String::endsWith($str, 'ring')); // 1
라이브러리 가득 기타 편리한 총괄하였습니다.
이 작동할 수 있다
function startsWith($haystack, $needle) {
return substr($haystack, 0, strlen($needle)) == $needle;
}
이 기능은 '거짓' 많다 '' substr 복귀하십시오 특수한 경우 이제 이러한 문제를 다룬 것은 나의 버전:
function startsWith( $haystack, $needle ){
return $needle === ''.substr( $haystack, 0, strlen( $needle )); // substr's false => empty string
}
function endsWith( $haystack, $needle ){
$len = strlen( $needle );
return $needle === ''.substr( $haystack, -$len, $len ); // ! len=0
}
테스트 ('true' 는 좋은):
var_dump( startsWith('',''));
var_dump( startsWith('1',''));
var_dump(!startsWith('','1'));
var_dump( startsWith('1','1'));
var_dump( startsWith('1234','12'));
var_dump(!startsWith('1234','34'));
var_dump(!startsWith('12','1234'));
var_dump(!startsWith('34','1234'));
var_dump('---');
var_dump( endsWith('',''));
var_dump( endsWith('1',''));
var_dump(!endsWith('','1'));
var_dump( endsWith('1','1'));
var_dump(!endsWith('1234','12'));
var_dump( endsWith('1234','34'));
var_dump(!endsWith('12','1234'));
var_dump(!endsWith('34','1234'));
또한 '약' 기능도 substr_compare 보았으매. http://www.php.net/manual/en/function.substr-compare.php