Search code examples
phpstrposampersand

PHP, Break Up String with Ampersand


I have spent a lot of time searching the web for this, so before someone slams me for not looking ... trust me, I have.

The problem: I am working with a string that includes an ampersand, to display two names. The difficulty: at times I may need to pull the name on the left, or the name on the right for display. The additional difficulty is that some of the names may include HTML entities, which of course also use an ampersand.

Example: I may use something as simple as:

"Fred & Wilma"

To get just "Fred" from the string, I tried using the PHP function STRPOS(), but I get nothing.

$nPos = strpos( " & ", $names );

Note that I am using spaces on either side to avoid issues with HTML entities.

More fun, checking to see if I get no results:

if ( $nPos === 0 )
{
   echo "String ' $' not found in " . $names . "<br />";
}

Does not return a value. This tells me, from the various documentation and such on the web that I can find, that I should have a value for $nPos that is useful.

If I add:

echo "Position of string ' & ': " . $nPos . "<br />";

I get a blank value after the text in double quotes.

I am at a loss how to do what I need here. I need to get the position of the " & " characters, but am not getting it. From there obviously use of the substr() function would be necessary to get the values from the left and/or right of the ampersand.


Solution

  • strpos first parameter is haystack - string in which you do the search & second is needle - string you searching for. So just swap parameters: $nPos = strpos( $names, " & " );

    You can find more info here