Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the portion of a string before the first occurrence of a character in PHP [duplicate]

Tags:

string

php

In PHP, what is the simplest way to return the portion of a string before the first occurrence of a specific character?

For example, if I have a string...

"The quick brown foxed jumped over the etc etc."

...and I am filtering for a space character (" "), the function would return "The".

like image 549
Travis Avatar asked Sep 22 '10 04:09

Travis


People also ask

How do you get a string before a specific character in PHP?

The easiest way to get a substring before the first occurrence of a character such as a whitespace is to use the PHP strtok() function. Pass the string to check as the first argument and the character to look for as the second.

Which function returns a part of a string in PHP?

The substr() function returns a part of a string.

How do I cut a string after a specific character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How do I slice a string in PHP?

The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.


2 Answers

For googlers: strtok is better for that:

echo strtok("The quick brown fox", ' '); 
like image 193
user187291 Avatar answered Oct 19 '22 00:10

user187291


You could do this:

$string = 'The quick brown fox jumped over the lazy dog'; $substring = substr($string, 0, strpos($string, ' ')); 

But I like this better:

list($firstWord) = explode(' ', $string); 
like image 23
Jacob Relkin Avatar answered Oct 19 '22 00:10

Jacob Relkin