2011-11-06 75 views
2

之间的空格在PHP我需要比较2个字符串。PHP字符串比较考虑在

str1="this is    a  string"
str2=" this is a string "

我要考虑str1和str2的是相同的字符串。

我能想到的方式是:

先修整字符串。首先提取每个字符串的单词,比较单词,然后得到结果。

任何更好的方法,即插入功能或其他东西来进行比较?

回答

5

只需使用preg_replace() functiontrim() function。以下:

<?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); 

将输出两个相同的字符串:

string(16) "this is a string" 
string(16) "this is a string" 

this codepad作为证据。

+1

Gaaaaaah。我想+1,但不能忽略使用'''作为正则表达式分隔符... –

+0

谢谢,我错过了 - ''''s +'“'字符串可以被替换为例如。如果你愿意的话,可以用'/'s + /''或'<\s+>'。 – Tadeck

+0

@MarcB:我将分隔符从'''改为'/',这样你就可以立刻投票;) – Tadeck

2

$str = preg_replace("/ +/"," ",$str);有什么不对?只需将多个空格合并成一个...

此外,请开始接受您的旧问题的答案。

+1

不会处理str2中主要字符串之前/之后的额外空间。你也需要修剪()两个字符串。 –