在PHP我需要比较2个字符串.
str1="this is a string"
str2=" this is a string "
我想将str1和str2视为相同的字符串.
我能想到的方式是:
首先修剪弦乐.首先提取每个字符串的单词,比较单词然后得到结果.
任何更好的方式,即bulit-in功能或其他东西来进行比较?
只需使用preg_replace()功能和trim()功能.下列:
<?php
$str1 = "this is a string";
$str2 = " this is a string ";
$str1 = preg_replace('/\s+/', ' ', trim($str1));
$str2 = preg_replace('/\s+/', ' ', trim($str2));
var_dump($str1, $str2);
Run Code Online (Sandbox Code Playgroud)
将输出两个相同的字符串:
string(16) "this is a string"
string(16) "this is a string"
Run Code Online (Sandbox Code Playgroud)
请参阅此键盘作为证明.