11/7/2023 0 Comments Php substring first occurrence![]() ![]() ![]() First containing all characters up to the nth occurrence of the needle (not included), and second from the nth occurrence of the needle (included) to the end. * at the beginning like this: $sResult = preg_replace("'.* ".$pControl.". Then you just use the mysplit function, and youll get an array with two substrings. Find the position of the first occurrence of one or more substrings in a string. Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). To get everything past the last By if you think there might be more than one, add an extra. Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. $pControl = "" //1 or 2 numbers followed by 2 lowercase letters.įor case insensitive, add the i modifier like this: $sResult = preg_replace("' ".$pControl.".*'si", '', $sInputString) $sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString) įor example, if you wanted to remove everything after the day: $sInputString = "Posted On April 6th By Some Dude" $sInputString = "Posted On April 6th By Some Dude" ![]() This method is also more flexible and allows you to do any regular expression. If you think By might exist more than once and want to cut everything after the last occurrence, use strrpos.īelow is a less efficient method but it takes up less code space. If you don't want to be case sensitive, use stripos instead of strpos. $sResult = substr($sInputString, 0, $iPosition) $iPosition = strpos($sInputString, " ".$sControl) What about using just PHPs built in function strripos() Finds the position of the last occurrence of a string inside another string. $sInputString = "Posted On April 6th By Some Dude" The strstr() function and its case-insensitive cousin stristr() is a nice and easy function that finds the first occurrence of a substring (parameter two). If By does not exist, the full string is returned. Example 1 Using a negative offset length If length is given and is positive, the string returned will contain at most length characters beginning from offset (depending on the length of string ).Below is the most efficient method (by run-time) to cut off everything after the first By in a string. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |