Cut a string when it finds a certain character with PHP
ok so lets say we have a string like this:
Hi there im a string. I am also part of the same string.
And we want to shorten the above string into just:
Hi there im a string.
This is what i would do:
$my_string = "Hi there im a string. I am also part of the same string.";
$dot_location = strpos($my_string,".");
Now we have the location of the "dot" or . well it looks like a dot.
Now we have this location we can use the substr function to cut that string at the dot location.
$my_string_cut = substr($my_string, 0, $dot_location);
Now if we echo the $my_string_cut we should get Hi there im a string.
echo $my_string_cut;
Ok so now, what if we wanted to get the second part of the above string rather than just the 1st part.
Its kinda the same, but we need to look for the second dot. and so we cant cheat and just grab it all the way to the end of the string ill add a bit more to the demo string.
New string is:
Hi there im a string. I am also part of the same string. I'm on the end of the string now!
$my_string = "Hi there im a string. I am also part of the same string. I'm on the end of the string now!";
$dot_location_one = strpos($my_string,".");
Now use the offset to skip to the next dot. So it should start looking for the next dot after the 1st dot location.
$dot_location_two = strpos($my_string,".", $dot_location_one);
so now we have both locations of the dots, and we can cut the main string with substr.
$my_string_cut_two = substr($my_string, $dot_location_one, $dot_location_two);