Long answer, sorry..
coupla things.
first I'll answer the question, then offer what might be a better solution (though it takes more work).
To detect the presence of a comma, you can use strpos or preg_match (and other fxns).
strpos returns the position of the first occurrence of a string within a string, which could be 0. This is not to be mistaken for FALSE (return for no match), but in the "last, first" scenario it's probably not applicable.
$hasComma = FALSE != strpos($trimmed, ',');
# or
$hasComma = preg_match('/,/',$trimmed,$m);
or, you could just explode on the comma and count the result.
$parts = explode(',', $trimmed);
$hasComma = count($parts)>1;
if there was a comma, and you're ok with assuming the user put in "last, first" (also assuming/checking that count($parts)==2 ), you can flip like so.
list( $first, $last ) = $parts;
if( $hasComma )
list($last, $first) = array($first, $last);
doing any exploding at all, you might want to trim all the parts so that you might reconstruct them in a controlled manner.
$parts = array_map("trim", $parts);
// I also like to filter empty parts
$parts = array_values( array_filter( $parts ));
Then your search term can be reconstructed
$term = join(' ',array($first, $last));
----------------
Now, I've gotta say that I don't think you've got an ideal search. What you might want to is break the search term apart (by space, comma, etc) and query an index of individual words. This is how you can rank of "relevance" and offer more results than you would have if the user misspelled their search term (which 5%-15% of users will always do).
By "index" I mean a new table containing "terms" and their associative artist_ids.
Let's take an example data set of three artists:
1- Johnny Cash
2- Sweep the Leg Johnny
3- Clean Sweep
Ignoring "the", our index of unique words is:
Johnny
Cash
Sweep
Leg
Clean
The linking table could look like:
_term_|_artist_id_
Johnny | 1
Cash | 1
Sweep | 2
Leg | 2
Johnny | 2
Clean | 3
Sweep | 3
Gather up possible matches for each word, paying special attention to when the same records appear. That should increase their relevance. Misses should decrease the "score". Then present your results in order of score. It's often better to show more results than fewer.
Before, a search for 'Sweep Johnny' would net 0 results, but we've all come to expect the search to be more lenient with our brevity. If we searched an index for each word, I'd get all three results, but I'd get exactly what I was looking for on the top.
#1 Sweep the Leg Johnny (100% 2/2)
#2 Johnny Cash (50% 1/2)
#3 Clean Sweep (50% 1/2)