tags:

views:

126

answers:

7

String comparison in PHP seems little difficult. I don't know if any other ways to do it.

For example say:

$t1 = "CEO";
$t2 = "Chairman";
$t3 = "Founder";

$title = "CEO, Chairman of the Board";

if (!strcmp($t1, $title)) {
    echo $title."<br>"; echo $Fname."<br>"; echo $Lname."<br>";
} else if (!strcmp($t2, $title)) {
    echo $title."<br>"; echo $Fname."<br>"; echo $Lname."<br>";
} else if (!strcmp($t3, $title)) {
    echo $title."<br>"; echo $Fname."<br>"; echo $Lname."<br>";
}

This isn't giving any result as above $title has word $t1 and $t2 in it. How can I do this?

A: 

Try splitting title on "," and using in_array... or strcmp on the individual parts of the array... or finding a whole new and better solution.

Fosco
+2  A: 

I assume you want to print that string if either of $t1, $t2, $t3 occurs in $title:

foreach (array($t1, $t2, $t3) as $titlePart) {
    if (strpos($title, $titlePart) !== false) {
        echo $title . "<br>" . $Fname . "<br>" . $Lname . "<br>";
        break;
    }
}
soulmerge
+8  A: 

The strcmp() tests on exact equality. You rather want to test if the string contains the given part. In that case rather use stripos() or stristr(). Both can be used the following way:

if (stripos($title, $t1) === false) {
    // $title does not contain $t1
}
if (stristr($title, $t1) === false) {
    // $title does not contain $t1
}

When you want case sensitive comparison (e.g. chairman should not be equal to Chairman), then use strpos() or strstr() instead.

BalusC
I will second strpos()
gnomixa
A: 

maybe this is what you want?

$t1 = "CEO";
$t2 = "Chairman";
$t3 = "Founder";

$title = "CEO, Chairman of the Board";

if (!is_integer(strpos($t1, $title))) {
    echo $title."<br>"; echo $Fname."<br>"; echo $Lname."<br>";
} else if (!sis_integer(strpos($t2, $title))) {
    echo $title."<br>"; echo $Fname."<br>"; echo $Lname."<br>";
} else if (!is_integer(strpos($t3, $title))) {
    echo $title."<br>"; echo $Fname."<br>"; echo $Lname."<br>";
}
Kris
A: 

Not sure what exactly you are attempting to do.

If you are simply checking for existance or position use strpos()

$t1 = "CEO";

$title = "CEO, Chairman of the Board";

$startposition = strpos($title, $t1);

if ($startposition === false) {
     //not found
} else {
   //found (@ index $startposition)
}

Again, not 100% sure what you are trying to find/do from this data, but hopefully that'll get you in the right direction.

Taylor
A: 
if (stripos($title, $t1) !=  false && stripos($title, $t2) !=  false && stripos($title, $t3) !=  false ) {
    echo $Fname ."<br />" . $Lname ; 
}

based on your comment - this is what you want. If t1, t2 and t3 ALL occur then print out first name and last name.

gnomixa
A: 

You might want to use preg_match() or strcasecmp() when searching strings like this, because those can ignore case. strcomp() is case sensitive and wont catch "CEO, chairman of the Board", for example.

GrandmasterB