Reputation: 6498
in php i need to compare 2 strings.
str1="this is a string"
str2=" this is a string "
I want to consider str1 and str2 to be the same string.
The way I can think is:
trim the strings first. extract the words of each string first, compare the words and then get the result.
Any better way i.e. bulit-in function or something else to make the comparison?
Upvotes: 3
Views: 4289
Reputation: 137420
Just use preg_replace()
function and trim()
function. The following:
<?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);
will output two identical strings:
string(16) "this is a string"
string(16) "this is a string"
See this codepad as a proof.
Upvotes: 10
Reputation: 324760
What's wrong with $str = preg_replace("/ +/"," ",$str);
? Just collapse multiple spaces into one...
Also, please start accepting answers on your older questions.
Upvotes: 2