PHP StartsWith () ve EndsWith () işlevleri

20 Cevap php

Onu nasıl belirtilen karakter / dizesi ile başlar veya onunla biter eğer bir dize almak ve dönecekti iki fonksiyon yazabilirim?

Örneğin:

$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true

20 Cevap

function startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}
function endsWith($haystack, $needle)
{
    return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}

var_dump(startsWith("hello world", "hello")); // true
var_dump(endsWith("hello world", "world"));   // true

GÜNCELLEME: iğne boş bir dize ise Java ve .NET implementations String.StartsWith ve String.EndsWith gerçek döndürür. Cevap buna göre revize edilmiştir.

GÜNCELLEME: MrHus's startsWith function, büyük samanlıkta için hızlıdır.

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);
}

Bir regex kullanmak istemiyorsanız, bu kullanın.

Tüm cevaplar kadar vb gereksiz iş, strlen hesaplamalar, string tahsisleri (substr), yükler yapmak gibi 'strpos' ve 'stripos' fonksiyonları $ samanlık $ iğne ilk geçtiği dizin dönmek:

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);
}

Credit To:

Check if a string ends with another string

Check if a string begins with another string

Yukarıdaki regex fonksiyonlar, aynı zamanda yukarıda önerilen diğer tweaks:

 function startsWith($needle, $haystack) {
     return preg_match('/^' . preg_quote($needle, '/') . '/', $haystack);
 }

 function endsWith($needle, $haystack) {
     return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
 }

Hız sizin için önemli ise, bu deneyin. (Ben hızlı yöntemi olduğuna inanıyorum)

Sadece dizeleri için çalışır ve $ samanlık sadece 1 karakter ise

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

Ben bu bitmiş oldu farkındayım, ama sen bu kadar karşı karşılaştırmak için dize uzunluğunu koymak sağlar gibi strncmp bakmak isteyebilirsiniz:

function startsWith($haystack, $needle, $case=true) {
    if ($case)
        return strncasecmp($haystack, $needle, strlen($needle)) == 0;
    else
        return strncmp($haystack, $needle, strlen($needle)) == 0;
}

kısacası:

function startsWith($str, $needle){
   return substr($str, 0, strlen($needle)) === $needle;
}

function endsWith($str, $needle){
   $length = strlen($needle);
   return !$length || substr($str, - $length) === $needle;
}

Kısa ve düzenli ifadeler olmadan tek gömlekleri kolay-anlamak için.

StartsWith () yalındır.

function startsWith($haystack, $needle) {
   return (strpos($haystack, $needle) === 0);
}

EndsWith () biraz fantezi ve yavaş strrev kullanır ():

function endsWith($haystack, $needle) {
   return (strpos(strrev($haystack), strrev($needle)) === 0);
}

Ben aşağıda cevap verimli ve aynı zamanda basit olabilir umuyoruz:

$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';

Ayrıca normal ifadeleri kullanabilirsiniz:

function endsWith($haystack, $needle, $case=true) {
  return preg_match("/.*{$needle}$/" . (($case) ? "" : "i"), $haystack);
}

substr function false çok özel durumlarda, bu nedenle burada bu konularla ilgilenen benim sürümüdür dönebilirsiniz:

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
}

Testler (true iyi anlamına gelir):

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'));

Also, the substr_compare function also worth looking. http://www.php.net/manual/en/function.substr-compare.php

Bu işe yarayabilir

function startsWith($haystack, $needle) {
     return substr($haystack, 0, strlen($needle)) == $needle;
}

Source: http://stackoverflow.com/a/4419658

Eğer dizeleri karşılaştırma öncesi, ilk karakter üzerinde bir test ekleme, boş olmadığından emin değilseniz StartsWith üzerinde yoğunlaşırken, strlen, vb şeyleri biraz hızlandırır:

function startswith5b($haystack, $needle) {
    return ($haystack{0}==$needle{0})?strncmp($haystack, $needle, strlen($needle)) === 0:FALSE;
}

Daha hızlı (20% -30%) her nasılsa. $ Samanlık gibi başka bir karakter testi, ekleme {1} === $ iğne {1}, çok şeyi hızlandırmak için bile yavaşlatmak görünmüyor.

=== seems faster than == Conditional operator (a)?b:c seems faster than if(a) b; else c;


For those asking "why not use strpos?" calling other solutions "unnecessary work"


strpos hızlı, ancak bu iş için doğru aracı değildir.

Anlamak için, burada örnek olarak küçük bir simülasyon olduğunu:

Search a12345678c inside bcdefga12345678xbbbbb.....bbbbba12345678c

What the computer does "inside"?

    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

Strlen varsayarsak bütün dize yinelemek değil (ama o durumda bile) bu hiç de uygun degildir.

Burada geçici bir dize tanıtmak değil iki işlev iğne ölçüde büyük olduğu zaman yararlı olabilir ki, şunlardır:

function startsWith($haystack, $needle)
{
    return strncmp($haystack, $needle, strlen($needle)) === 0;
}

function endsWith($haystack, $needle)
{
    return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}

Neden aşağıdaki değil?

//How to check if a string begins with another string
$haystack = "valuehaystack";
$needle = "value";
if (strpos($haystack, $needle) === 0){
    echo "Found " . $needle . " at the beginning of " . $haystack . "!";
}

Çıktı:

Valuehaystack başında değer bulundu!

Unutmayın, iğne samanlıkta bulunmazsa, strpos return false, ve 0 eğer dönecektir, ve iğne indeks 0 (AKA başlangıcı) bulunmuştur ancak, eğer.

Ve burada EndsWith bulunuyor:

$haystack = "valuehaystack";
$needle = "haystack";

//If index of the needle plus the length of the needle is the same length as the entire haystack.
if (strpos($haystack, $needle) + strlen($needle) === strlen($haystack)){
    echo "Found " . $needle . " at the end of " . $haystack . "!";
}

Bu senaryoda bir işlev StartsWith gerek () olarak orada

(strpos($stringToSearch, $doesItStartWithThis) === 0)

doğru doğru veya yanlış dönecektir.

Bu tüm yabani fonksiyonlar burada yaygın çalışan bu basit tuhaf görünüyor.

James Black'in cevap dayalı, burada onun EndsWith versiyonu:

function startsWith($haystack, $needle, $case=true) {
    if ($case)
        return strncmp($haystack, $needle, strlen($needle)) == 0;
    else
        return strncasecmp($haystack, $needle, strlen($needle)) == 0;
}

function endsWith($haystack, $needle, $case=true) {
     return startsWith(strrev($haystack),strrev($needle),$case);

}

Not: strncasecmp aslında strncmp harf duyarsız versiyonu çünkü, James Black'in StartsWith fonksiyonu için if-else bölümünü takas.

PHP 4 için etkili bir çözümdür. Siz substr_compare yerine strcasecmp(substr(...)) ile PHP 5 üzerinde hızlı sonuç ise alabilir.

function stringBeginsWith($haystack, $beginning, $caseInsensitivity = false)
{
    if ($caseInsensitivity)
        return strncasecmp($haystack, $beginning, strlen($beginning)) == 0;
    else
        return strncmp($haystack, $beginning, strlen($beginning)) == 0;
}

function stringEndsWith($haystack, $ending, $caseInsensitivity = false)
{
    if ($caseInsensitivity)
        return strcasecmp(substr($haystack, strlen($haystack) - strlen($ending)), $haystack) == 0;
    else
        return strpos($haystack, $ending, strlen($haystack) - strlen($ending)) !== false;
}

Önceki cevapların çoğu gibi iyi çalışacaktır. Ancak, bu bunu yapmak ve bunu arzu ne olabilir gibi muhtemelen kısa.

function startsWith($haystack, $needle)
{
    return $needle ? strpos($haystack, $needle) === 0 : "";
}

function endsWith($haystack, $needle)
{
    return $needle ? substr($haystack, -strlen($needle)) === $needle : "";
}
function startsWith($haystack, $needle){    
   $l = strlen($needle);
   for($i =0 ;$i<$l;$i++)
        if($needle[$i]!=$haystack[$i])
              return false;
    return true;
}

Ben çözüm bu tür should hızlı olmak düşünüyorum. (Ben ne boş $haystack ve / veya boş $needle, yazma gibi endsWith fonksiyonunu işleme zaman aldı bilmiyorum. Onun için meydan!)


Bu regexp ben arıyordum:

$starts_with = preg_match('/^$neddle_letters/',$haystack)?"yes":"no";

nerede

  • /-s dize sıradanifade demektir
  • ^ başlar ile gelir
  • preg_match returns array ( 0 => $neddle) if found(, nerede0 means first match, not 0.position)
  • ve boş dizisi değil
  • $neddle_letters özel karakter içermemeli - gibi: $|^()[]<>{}+-\:*=?!. - onlar sadece escaped
  • onunla oynayabilirsiniz here