fishfin Posted June 15, 2008 Share Posted June 15, 2008 Is there any way to count the number of instances of a string inside of a longer string? An example would be counting the number of 'e's in 'I like to eat sheep.' Quote Link to comment https://forums.phpfreaks.com/topic/110284-counting/ Share on other sites More sharing options...
Daniel0 Posted June 15, 2008 Share Posted June 15, 2008 echo substr_count('e', 'I like to eat sheep'); Quote Link to comment https://forums.phpfreaks.com/topic/110284-counting/#findComment-565873 Share on other sites More sharing options...
fishfin Posted June 15, 2008 Author Share Posted June 15, 2008 Could I also do this? $x = substr_count('e', 'I like to eat sheep'); And another thing, how would I tell it to count the number of <enter>'s in the string? Quote Link to comment https://forums.phpfreaks.com/topic/110284-counting/#findComment-565878 Share on other sites More sharing options...
Daniel0 Posted June 15, 2008 Share Posted June 15, 2008 Could I also do this? $x = substr_count('e', 'I like to eat sheep'); Yes. And another thing, how would I tell it to count the number of <enter>'s in the string? \n means a new line, so you can do: substr_count("\n", $string); Note that it won't work if you use single quotes. Quote Link to comment https://forums.phpfreaks.com/topic/110284-counting/#findComment-565879 Share on other sites More sharing options...
Barand Posted June 15, 2008 Share Posted June 15, 2008 And another thing, how would I tell it to count the number of <enter>'s in the string? <?php $string = "Twas brillig and the slithy toves Did gyre and gimble in the wabe All mimsy were the borogoves And the mome raths outgrabe"; $count = substr_count($string, "\n"); // NOTE (haystack, needle) echo $count; // --> 3 ?> Quote Link to comment https://forums.phpfreaks.com/topic/110284-counting/#findComment-565880 Share on other sites More sharing options...
Daniel0 Posted June 15, 2008 Share Posted June 15, 2008 Oh... it seems I got the order of the arguments wrong. Thanks, Barand. Quote Link to comment https://forums.phpfreaks.com/topic/110284-counting/#findComment-565881 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.