質問
文字列を受け取り、指定された文字/文字列で始まるか、文字列で終わる場合に返す2つの関数を作成するにはどうすればよいですか?
例:
$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);
}
正規表現を使用しない場合は、これを使用します。
他のヒント
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で最も高速なソリューションの1つです(ベンチマークスクリプト) 。 8KBの干し草の山、さまざまな長さの針、完全な、部分的な、および一致しないケースに対してテストされています。 strncmp
は、starts-withの方が高速ですが、ends-withをチェックできません。
2016年8月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";
}
結果(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
これまでのすべての答えは、不要な作業、 strlen計算
、 string allocations(substr)
などを大量に実行するようです。 'strpos'
および 'stripos'
関数は、 $ haystack
で最初に出現する $ needle
のインデックスを返します。
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);
}
クレジットの宛先:
上記の正規表現は機能しますが、上記で提案した他の微調整もあります:
function startsWith($needle, $haystack) {
return preg_match('/^' . preg_quote($needle, '/') . '/', $haystack);
}
function endsWith($needle, $haystack) {
return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
}
この質問にはすでに多くの答えがありますが、場合によっては、すべての質問よりも簡単なものを選ぶことができます。 探している文字列がわかっている(ハードコードされている)場合、引用符などを付けずに正規表現を使用できます。
文字列が「ABC」で始まるかどうかを確認します:
preg_match('/^ABC/', $myString); // "^" here means beginning of string
「ABC」で終わる:
preg_match('/ABC$/', $myString); // "preg_match('#/$#', $myPath); // Use "#" as delimiter instead of escaping slash
quot; here means end of string
単純なケースでは、文字列がスラッシュで終わるかどうかを確認したかった:
<*>利点:非常に短くて単純なので、上記のように関数( endsWith()
など)を定義する必要はありません。
しかし、これはすべての場合の解決策ではなく、この非常に具体的な解決策です。
速度が重要な場合は、これを試してください(最速の方法だと思います)
文字列に対してのみ機能し、$ haystackが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
一時的な文字列を導入しない2つの関数を次に示します。これは、針がかなり大きい場合に役立ちます。
function startsWith($haystack, $needle)
{
return strncmp($haystack, $needle, strlen($needle)) === 0;
}
function endsWith($haystack, $needle)
{
return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
これが終了したことは承知していますが、 strncmp を使用すると、比較する文字列の長さを入力できるため、
function startsWith($haystack, $needle, $case=true) {
if ($case)
return strncasecmp($haystack, $needle, strlen($needle)) == 0;
else
return strncmp($haystack, $needle, strlen($needle)) == 0;
}
Fastest endsWith()ソリューション:
# 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
$bStartsWith = strpos($sHaystack, $sNeedle) == 0;
$bEndsWith = strrpos($sHaystack, $sNeedle) == strlen($sHaystack)-strlen($sNeedle);
正規表現なしの短くてわかりやすいワンライナー。
startsWith()は簡単です。
function startsWith($haystack, $needle) {
return (strpos($haystack, $needle) === 0);
}
endsWith()は、少し派手で遅いstrrev()を使用します:
function endsWith($haystack, $needle) {
return (strpos(strrev($haystack), strrev($needle)) === 0);
}
受け入れられた回答のマルチバイトセーフバージョンは次のとおりです。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);
}
startswithに焦点を当て、文字列が空でないことが確実な場合、最初の文字にテストを追加し、比較の前に、strlenなどを使用して、物事を少しスピードアップします。
function startswith5b($haystack, $needle) {
return ($haystack{0}==$needle{0})?strncmp($haystack, $needle, strlen($needle)) === 0:FALSE;
}
それはどういうわけか(20%-30%)高速です。 $ haystack {1} === $ needle {1}のような別のcharテストを追加しても、物事はそれほどスピードアップしないようで、さらには遅くなる可能性があります。
===
は ==
より速いようです
条件演算子(a)?b:c
は if(a)b;よりも速いようです。 else c;
「strposを使用しないのはなぜですか?」他のソリューションを呼び出す&quot;不必要な作業&quot;
strposは高速ですが、このジョブに適したツールではありません。
理解するために、ここに例として小さなシミュレーションを示します:
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
strlenが文字列全体を反復しないと仮定した場合(ただしその場合でも)、これはまったく便利ではありません。
以下の答えが効率的でシンプルであることを願っています:
$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';
私は通常、最近 underscore-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
ライブラリには他の便利な関数がいっぱいです。
回答による mpen は非常に徹底的ですが、残念ながら、提供されたベンチマークには非常に重要で有害な監視があります。
針と干し草のすべてのバイトは完全にランダムであるため、針と干し草のペアが最初のバイトで異なる確率は99.609375%です。これは、平均で、100000ペアの約99609が非常に最初のバイト。言い換えると、ベンチマークは、 strncmp_startswith2
と同様に、最初のバイトを明示的にチェックする startswith
実装に大きく偏っています。
代わりに、テスト生成ループが次のように実装されている場合:
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
もちろん、このベンチマークはまだ完全に公平ではないかもしれませんが、部分的に一致する針が与えられたときにアルゴリズムの効率をテストします。
substr
関数は多くの特別な場合に false
を返すことがあるため、これらの問題に対処する私のバージョンは次のとおりです。
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
要するに:
function startsWith($str, $needle){
return substr($str, 0, strlen($needle)) === $needle;
}
function endsWith($str, $needle){
$length = strlen($needle);
return !$length || substr($str, - $length) === $needle;
}
これは動作する可能性があります
function startsWith($haystack, $needle) {
return substr($haystack, 0, strlen($needle)) == $needle;
}
次はどうですか?
//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 . "!";
}
出力:
valuehaystackの先頭に値が見つかりました!
strpos
は、干し草の山で針が見つからなかった場合はfalseを返し、インデックス0(先頭)で針が見つかった場合にのみ0を返します。
そしてこれで終わりです:
$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 . "!";
}
このシナリオでは、関数startsWith()asの必要はありません
(strpos($stringToSearch, $doesItStartWithThis) === 0)
trueまたはfalseを正確に返します。
ここでは、すべての野生の機能が横行しているので、これは簡単なように見えます。
このようにします
function startWith($haystack,$needle){
if(substr($haystack,0, strlen($needle))===$needle)
return true;
}
function endWith($haystack,$needle){
if(substr($haystack, -strlen($needle))===$needle)
return true;
}
推奨事項:
function startsWith($haystack,$needle) {
if($needle==="") return true;
if($haystack[0]<>$needle[0]) return false; // ------------------------- speed boost!
return (0===substr_compare($haystack,$needle,0,strlen($needle)));
}
追加の行は、文字列の最初の文字を比較して、 偽のケースが即時を返すため、多くの比較を行います はるかに高速(測定すると7倍高速)。本当の場合、その単一ラインのパフォーマンスに実質的に価格を支払うことはないので、含める価値があると思います。 (また、実際には、特定の開始チャンクについて多くの文字列をテストする場合、通常の場合は何かを探しているため、ほとんどの比較は失敗します。)
正規表現も使用できます:
function endsWith($haystack, $needle, $case=true) {
return preg_match("/.*{$needle}$/" . (($case) ? "" : "i"), $haystack);
}
これまでの回答の多くも同様に機能します。しかし、これはおそらくあなたがそれを作り、あなたが望むものをやらせることができる限り短いです。あなたはそれが「真に戻りたい」と述べるだけです。そのため、ブール値のtrue / falseおよびテキストのtrue / falseを返すソリューションを含めました。
// boolean true/false
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0 ? 1 : 0;
}
function endsWith($haystack, $needle)
{
return stripos($haystack, $needle) === 0 ? 1 : 0;
}
// textual true/false
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0 ? 'true' : 'false';
}
function endsWith($haystack, $needle)
{
return stripos($haystack, $needle) === 0 ? 'true' : 'false';
}
ジェームス・ブラックの答えに基づいて、ここにその終わりがありますバージョン:
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);
}
注:strncasecmpは実際にはstrncmpの大文字と小文字を区別しないバージョンであるため、James BlackのstartsWith関数のif-else部分を交換しました。
こちらはPHP 4の効率的なソリューションです。PHP5では、 strcasecmp(substr(...))の代わりに
substr_compare
を使用すると、より高速な結果が得られます。 code>。
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;
}
$ends_with = strrchr($text, '.'); // Ends with dot
$start_with = (0 === strpos($text, '.')); // Starts with dot
これがなぜ人々にとってこれほど難しいのかはわかりません。 Substrは、文字列全体が一致しない場合でも検索する必要がないため、非常に効率的です。
さらに、整数値をチェックするのではなく、文字列を比較するので、厳密な===の場合を必ずしも心配する必要はありません。ただし、===に入るのは良い習慣です。
function startsWith($haystack,$needle) {
substring($haystack,0,strlen($needle)) == $needle) { return true; }
return false;
}
function endsWith($haystack,$needle) {
if(substring($haystack,-strlen($needle)) == $needle) { return true; }
return false;
}
またはさらに最適化されています。
function startsWith($haystack,$needle) {
return substring($haystack,0,strlen($needle)) == $needle);
}
function endsWith($haystack,$needle) {
return substring($haystack,-strlen($needle)) == $needle);
}