Get first word in string php
If you want to know how fast each of these respective functions is, I ran some crude benchmarking in PHP 7.3 on the six most voted answers here ( Show
Here are the varying results from 2 consecutive runs:
And the results after inverting the order of the functions:
Conclusion It turns out that the speed between these functions varies widely and is not as consistent between test runs as you might expect. According to these quick and dirty tests, any of the six chosen functions will get the job done in a reasonable amount of time. There are perturbations including other processes running that are interfering with the execution times. So just use whatever function makes the most practical and readable sense to you as a programmer. For the bigger programming picture, see Donald Knuth's Literate Programming. The first word of a sentence can be obtained with the help of various inbuilt functions like strtok(), strstr(), explode() and some other methods like using regular expressions. Some examples to get the first word of a sentence are listed below: Method 1: Using strtok() Function: This function is used to tokenize a string into smaller parts on the basis of given delimiters. It takes input String as an argument along with delimiters (as second argument). Syntax: string strtok( $string, $delimiters ) Program:
Output: The first word of string is: Welcome Method 2: Using trim() and explode() Function:
Program:
Output: The first word of string is: Welcome Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string. This function is case-sensitive. Syntax: strstr( $string, $search, $before ) Program:
Output: The first word of string is: Welcome Method 4: Using preg_match() Function: This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search. Syntax: int preg_match( $pattern, $input, $matches, $flags, $offset ) Program:
Output: The first word of string is: Welcome How to get first word in PHP string?echo "The first word of string is: " . $arr [0]; ?> Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string.
What is Strstr PHP?Definition and Usage. The strstr() function searches for the first occurrence of a string inside another string. Note: This function is binary-safe. Note: This function is case-sensitive. For a case-insensitive search, use stristr() function.
How do I remove a word from a string in PHP?Answer: Use the PHP str_replace() function
You can use the PHP str_replace() function to replace all the occurrences of a word within a string.
|