14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[PHP]正規表現○○から始まる文字列か?○○で終わる文字列か?(preg_match)

Last updated at Posted at 2015-11-30

忘れそうなので取り急ぎメモっておきます!
なんかこれいっつもググってる気がしますし・・。

○○から始まる文字列か?

preg_match("/^○○/",$strhoge));

○○で終わる文字列か?

preg_match("/○○$/",$strhoge));

まとめ

^ を先頭につけると、○○から始まる文字列
$ を最後につけると、○○で終わる文字列

となります。

使用例

// 先頭
if (preg_match("/^○○/",$strhoge)) {
	echo '○○から始まっています';
}
else{
	echo '○○から始まっていません';
}

// 最後
if (preg_match("/○○$/",$strhoge)) {
	echo '○○で終わってます';
}
else{
	echo '○○で終わってません';
}

みたいに使えますね。

追記

PHPの場合は正規表現の処理は重いらしく、PHPの関数がある場合は使用した方が処理が早いようです。処理速度を気にする方は、こちらをおすすめします。

■strncmp — 最初の n 文字についてバイナリセーフな文字列比較を行う
http://php.net/manual/ja/function.strncmp.php

// 先頭
if (strncmp($strhoge,'○○', strlen('○○')) === 0) {
    echo '○○から始まっています';
}
else{
    echo '○○から始まっていません';
}
14
13
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?