Click to See Complete Forum and Search --> : Problem with string operation


szms
08-26-2003, 09:31 AM
Please take a look of the following code. While outputting the two string variables, I am getting the same sting with same amount of space. But while comaparing I am getting the output "Different" What kind of string operation I have to do so that I will get "Same". Thank you.



<?php
$name1 = " Hello World ");
$name2 = "Hello World";

print "Before: $name1<br>";
print "Before: $name2<br>";

if ($name1 == $name2)

print "Same";

else
print "Different";

?>

DaiWelsh
08-26-2003, 09:37 AM
You are only seeing the same string because your browser interprets successive whitespace characters (space, tab, new line etc.) as one space.

To get the strings to be genuinely the same you need to replace repeated spaces with one space. You can do this for example with regular expressions with something like (untested)

$clean1 = preg_replace('/\s+/',' ',$name1);
$clean2 = preg_replace('/\s+/',' ',$name2);

HTH,

Dai