point86 Posted February 14, 2007 Share Posted February 14, 2007 Hi, I have a string: $query = $_GET['words']; Where words are terms inputted by the user. IE $query will be something like 'hello how are you'. How do I get the system to search the string 'hello how are you' for SPACES (" ") and assign the number of spaces to a variable? EG in the string 'hello how are you', the number of spaces would be 3, and this would be assigned to eg $spaces. Thanks P86. Quote Link to comment Share on other sites More sharing options...
effigy Posted February 14, 2007 Share Posted February 14, 2007 This includes all whitespace. If you only want spaces, change '\s' to ' '. <pre> <?php $string = 'hello how are you'; $num_whitespace = 0; preg_replace('/\s/', '', $string, -1, $num_whitespace); echo $num_whitespace; ?> </pre> Quote Link to comment Share on other sites More sharing options...
Jessica Posted February 14, 2007 Share Posted February 14, 2007 http://us3.php.net/manual/en/function.substr-count.php They don't want to replace them, just count them. Quote Link to comment Share on other sites More sharing options...
effigy Posted February 14, 2007 Share Posted February 14, 2007 I didn't know that function existed. The "replace" isn't affecting anything though, it's being called in a void context. $string is never modified. Quote Link to comment Share on other sites More sharing options...
Jessica Posted February 14, 2007 Share Posted February 14, 2007 Good point. But yeah, I don't see any reason to use regexp here, since the built in function is likely faster or more efficient or something. Or I just want to be right Quote Link to comment Share on other sites More sharing options...
boo_lolly Posted February 14, 2007 Share Posted February 14, 2007 if you're pulling the string using $_GET, then it's coming from the address bar (probably not the best idea)... anyway, the address bar will replace spaces with the '+' symbol. use preg_replace() to replace + with whitespace. Quote Link to comment Share on other sites More sharing options...
hitman6003 Posted February 14, 2007 Share Posted February 14, 2007 Or use urldecode.... http://www.php.net/urldecode Quote Link to comment Share on other sites More sharing options...
point86 Posted February 14, 2007 Author Share Posted February 14, 2007 Worked great, thanks! P86. Quote Link to comment 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.