strpos ile dize sonuna kadar bir kelime eşleştirme

3 Cevap php

Solution: strpos turned out to be the most efficient. Can be done with substr but that creates a temporary substring. Can also be done with regex, but slower than strpos and does not always produce the right answer if the word contains meta-characters (see Ayman Hourieh comment).

Chosen cevap:

if(strlen($str) - strlen($key) == strrpos($str,$key))
    print "$str ends in $key"; // prints Oh, hi O ends in O

ve sıkı eşitlik için test etmek için en iyi === (David cevaba bakınız)

Yardım için herkese teşekkürler.


Ben o dizenin sonunda oluşur görmek için bir dize bir kelime maç için çalışıyorum. Her zamanki strpos($theString, $theWord); bunu yapmazdı.

Temelde ise $theWord = "my word";

$theString = "hello myword";        //match
$theString = "myword hello";        //not match
$theString = "hey myword hello";    //not match

Ne bunu yapmak için en etkili yol olacaktır?

P.S. Başlığı ben strpos dedi, ama daha iyi bir yolu varsa, o da ok bulunuyor.

3 Cevap

strpos bazı durumlarda en verimli olabilir, ama ikinci parametre dizenin sonundan itibaren geriye doğru saymak gibi aynı zamanda bir negatif bir değer ile substr yapabilirsiniz:

$theWord = "my word";
$theWordLen = strlen($theWord);

$theString = "hello myword";
$matches = ($theWord ==substr($theString, -1 * $theWordLen);

Bir regular expression kullanabilirsiniz.

if(preg_match('/'.$theWord.'$/', $theString)) {
    //matches at the end of the string
}

Yoksa strrpos() kullanımı ve kelimenin uzunluğunu ekleyebilirsiniz. (Strrpos - "Find position of last occurrence of a char in a string") bu dizesinde son karakterin konumudur olmadığını Sonra bakın.