どうも、ちょげ(@chogetarou)です。
文字列(string)の指定文字までを切り出す方法を紹介します。
方法

文字列(string)の指定文字までを切り出す方法は、2つあります。
explode()
ひとつは、explode()を使う方法です。
まず、explode()を呼び出します。
explode()の第1引数に指定文字、第2引数に対象の文字列を指定します。
そして、上記のexplode()の戻り値のインデックス「0」にアクセスします。
//char=指定文字, text=対象の文字列,
$result = explode(char, text)[0];
上記のexplode()のインデックス「0」にアクセスすることで、対象の文字列(string)の指定文字までを切り出せます。
使用例
<?php
$text = "Hello,World";
$result = explode(",", $text)[0];
echo $result;
?>
出力:
Hello
substr() + strpos()
もうひとつは、substr()とstrpos()を使う方法です。
まず、substr()を呼び出します。
substr()の第1引数に対象の文字列、第2引数に「0」、第3引数にstrpos()を指定します。
strpos()の第1引数に対象の文字列、第2引数に特定の文字を指定します。
//char=指定文字, text=対象の文字列,
$result = substr(text, 0, strpos(text, char));
上記のsubstr()は、対象の文字列(string)の指定文字までを切り出します。
もし、指定文字までを含めて、切り出したい場合は、上記のstrpos()の結果に「+1」します。
//指定文字を含めて切り出す
$result = substr(text, 0, strpos(text, char) + 1);

PHP: substr - Manual
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites i...

PHP: strpos - Manual
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites i...
使用例
<?php
$text = "Hello,World";
$result = substr($text, 0, strpos($text, ","));
echo $result;
?>
出力:
Hello
まとめ
文字列(string)の指定文字までを切り出す方法は、次の2つです。
- explode()を使う方法
$result = explode(char, text)[0]; - substr()とstrpos()を使う方法
$result = substr(text, 0, strpos(text, char));
コメント