etrader Posted January 24, 2011 Share Posted January 24, 2011 I want to catch the first word of a string in which the words are separated by "-" (e.g. "first-word-second-one-more"). I used this code: $string = explode('-', $string); echo $string[0]; The problem is that when the string contains only one word, it returns null :-\ Quote Link to comment https://forums.phpfreaks.com/topic/225493-getting-the-first-word-of-a-string/ Share on other sites More sharing options...
dragon_sa Posted January 24, 2011 Share Posted January 24, 2011 $catch=explode('-', $string); If ($catch[0]!=null) { echo $catch[0]; } else { echo $string; } Quote Link to comment https://forums.phpfreaks.com/topic/225493-getting-the-first-word-of-a-string/#findComment-1164378 Share on other sites More sharing options...
salathe Posted January 24, 2011 Share Posted January 24, 2011 The problem is that when the string contains only one word, it returns null :-\ No it doesn't. $string = "word"; $string = explode('-', $string); echo $string[0]; // word Quote Link to comment https://forums.phpfreaks.com/topic/225493-getting-the-first-word-of-a-string/#findComment-1164384 Share on other sites More sharing options...
etrader Posted January 24, 2011 Author Share Posted January 24, 2011 You are quite right! It was my stupid mistake, as the problem has come from another issue :-\ Sorry Quote Link to comment https://forums.phpfreaks.com/topic/225493-getting-the-first-word-of-a-string/#findComment-1164415 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.