3

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?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I missed that - the "'\s+'" string can be replaced by eg. '/\s+/' or '<\s+>' if you wish.
@MarcB: I changed delimiter from ' to / so you can upvote now ;)
2

What's wrong with $str = preg_replace("/ +/"," ",$str);? Just collapse multiple spaces into one...

Also, please start accepting answers on your older questions.

1 Comment

Wouldn't handle the extra space before/after the main string in str2. You'd need to trim() both strings as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.