foochuck Posted June 4, 2009 Share Posted June 4, 2009 I'm trying to figure out how to search through a variable for a given string. For example my variable is: $myVariable = 'may the force be with you'; I want to search through the variable to see if it contains 'the force'. Is there a function to do this? Thanks Link to comment https://forums.phpfreaks.com/topic/160986-search-for-a-string-in-a-variable/ Share on other sites More sharing options...
Alex Posted June 4, 2009 Share Posted June 4, 2009 strpos(). $myVariable = 'may the force be with you'; if(strpos($myVariable, 'the force') === false) { //the string was not found } else { //It was found.. } Link to comment https://forums.phpfreaks.com/topic/160986-search-for-a-string-in-a-variable/#findComment-849593 Share on other sites More sharing options...
foochuck Posted June 4, 2009 Author Share Posted June 4, 2009 Thanks Alex. One more question - could you show me how I could turn this into a function so I can feed two variables into strpos and then return a string of HTML if the string IS found...? strpos(). $myVariable = 'may the force be with you'; if(strpos($myVariable, 'the force') === false) { //the string was not found } else { //It was found.. } Link to comment https://forums.phpfreaks.com/topic/160986-search-for-a-string-in-a-variable/#findComment-849594 Share on other sites More sharing options...
foochuck Posted June 4, 2009 Author Share Posted June 4, 2009 One more question, could I just do this? $myVariable = 'may the force be with you'; if(strpos($myVariable, 'the force') === true) { //It was found.. } strpos(). $myVariable = 'may the force be with you'; if(strpos($myVariable, 'the force') === false) { //the string was not found } else { //It was found.. } Link to comment https://forums.phpfreaks.com/topic/160986-search-for-a-string-in-a-variable/#findComment-849595 Share on other sites More sharing options...
foochuck Posted June 4, 2009 Author Share Posted June 4, 2009 Someone just suggested this to me... if(strstr($myVariable,'the force')) { //It was found... } Would this work too? Link to comment https://forums.phpfreaks.com/topic/160986-search-for-a-string-in-a-variable/#findComment-849597 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.