Jump to content

How would I check if a string has a word in, and add it on if it doesn't exist?


TeddyKiller

Recommended Posts

Lets take a string..

$string = 'hello';

How would I check if that string, as the word "Re: " in it.

If it doesn't, to add it on. So the output would be in this case

Re: hello

 

If we took this string..

$string = 'Re: hello';

Checked if it has Re: in it.

It does have Re, in it.. so there for we don't add it on. Output would be..

Re: hello

 

How can I do this?

Thanks

Hmmm...

 

<?php

$haystack = "Subject";
$needle = "Re:";

$pos = strpos($haystack,$needle);

if($pos === false) {
// string needle NOT found in haystack
echo "Not found: " . $needle . " in " . $haystack;
}
else {
// string needle found in haystack
echo "Not found: " . $needle . " in " . $haystack;
}
echo "<br><br>";


$row['subject'] = "Re: Something";


$haystack = $row['subject'];
$needle = "Re:";

$pos = strpos($haystack,$needle);

if($pos === false) {
// string needle NOT found in haystack
echo "Not found: " . $needle . " in " . $haystack;
}
else {
// string needle found in haystack
echo "found: " . $needle . " in " . $haystack;
}
echo "<br><br>";

?>

Ah cheers, can you explain why it never worked for me in the first place?

 

This line: $pos = stripos('Re: ',$subject); was searching for the position of $row['subject'] in the string "Re: ".  In other words, your parameters were the wrong way around. See the stripos manual page.

Ah cheers, can you explain why it never worked for me in the first place?

 

This line: $pos = stripos('Re: ',$subject); was searching for the position of $row['subject'] in the string "Re: ".  In other words, your parameters were the wrong way around. See the stripos manual page.

 

Ah i understand. I thought having Re: infront of the string.. would look for the word infront, as if it was after it'd look if it was after the word. My mistake.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.