1
0

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で全角スペースのtrimのようなことをする

Last updated at Posted at 2018-02-01

とりあえず、何も考えずに第二引数のデフォルト値に全角スペースを入れてtrimしてみた。

$string = "  a bc \n \r \t";
$string = trim($string, "  \t\n\r\0\x0B");
var_dump($string);
string(6) "a bc"

普通にできたと思いきや、日本語にしてみる。

$string = "  あい う\n \r \t";
$string = trim($string, "  \t\n\r\0\x0B");
var_dump($string);
string(11) "��い う"

日本語に対応していないので別の方法を考える。
trimの挙動と異なるかもしれませんが今回は前後の空白文字を削除出来れば良しとします。

$string = "  あい う\n \r \t";
$string = mb_ereg_replace('^[\s ]+|[\s ]+$', '', $string);// \sは全角スペースを除く空白文字
var_dump($string);
string(12) "あい う"

できた!

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?