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.' 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'); 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? 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. 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 ?> 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. Link to comment https://forums.phpfreaks.com/topic/110284-counting/#findComment-565881 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.