Page 1 of 1

Problem with string operation

Posted: Tue Aug 26, 2003 9:31 am
by szms
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.

Code: Select all

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

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

if ($name1 == $name2)

    print "Same";

else
    print "Different";

?>

Posted: Tue Aug 26, 2003 9:37 am
by Orkan
If you take a look to your HTML code - you'll see that there ARE spaces... But IE cuts all spaces so that only one left. If you want to make more than one space - use &nbsp; comand instead of " ".
PHP tells you "different" cause they ARE different!

Posted: Tue Aug 26, 2003 9:43 am
by JayBird
Try this

Code: Select all

// Sorry, my code didn't actually work, deleted it to save confusion
Mark

Posted: Tue Aug 26, 2003 9:44 am
by szms
little example with code will help to understand better.

Posted: Tue Aug 26, 2003 10:03 am
by Orkan
Example:
if you write in file.html:

Code: Select all

something           anything        wateva
bla
you'll get:

Code: Select all

something anything wateva bla
to get

Code: Select all

something    anything    wateva    bla
use '& n b s p ;' w/o spaces between letters, not ' '!
(I placed spaces cause bug in forum accepts this text as html code, w/o converting special chars :()

Posted: Tue Aug 26, 2003 10:51 am
by JayBird
that isn't really what he is asking if you re-read the question. He want to know how to make these two line equal each other

Code: Select all

$name1 = "     Hello          World        "); 
$name2 = "Hello World";
What operation can be done so that $name1 and $name2 equal each other.

Posted: Tue Aug 26, 2003 11:01 am
by volka
I'm not quite sure what this is good for but anyway ;)

Code: Select all

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

// ignoring all spaces
// even if name2 is 'HelloWorld' this will print 'Same'
if (str_replace(' ', '', $name1) == str_replace(' ', '', $name2))
	print "Same";
else
	print "Different";
	
// removing whitespaces from start/end, then remove multiple-spaces within string
// if name2 is 'HelloWorld' this will print 'Different'
if ( preg_replace('/\s+/', ' ', trim($name1)) == preg_replace('/\s+/', ' ', trim($name2)) )
	print "Same";
else
	print "Different";	
?>