PHP get first word from string example

In this tutorial we will show you php get first word from string. You will simply learn how to get first word from string in PHP. You can see php get first word from string example.

We will use strtok() function to get first word from string. strtok() can split a string into tokens. By passing a space as the delimiter, you can get the first word easily.

1. PHP get first word from string using strtok() function

You can see and consider below example. You can get first word from string easily.

<?php

$newString = "Hello How are you";

$getFirstWord = strtok($newString, ' ');

echo $getFirstWord; // Output: Hello
?>
2. PHP get first word from string using explode() function

The explode() function splits a string into an array. You can use this to get the first element of the array, which will be the first word of the string.

<?php

$newString = "Hello How are you";

$getFirstWord = explode(' ', $newString)[0];

echo $getFirstWord; // Output: Hello
?>
3. PHP get first word from string using preg_match() function

A regular expression can match the first word of the string and get easily first word. This function searches string for pattern, return true if pattern exists, otherwise returns false.

<?php

 $newString = "Hello How are you";

 preg_match('/^\S+/', $newString, $matchValue);
 $getFirstWord = $matchValue[0];

 echo $getFirstWord; // Output: Hello
?>
4. PHP get first word from string using substr() and strpos() function

By finding the position of the first space and can extract the substring up to that point.

<?php

 $newString = "Hello How are you";
 $getFirstSpace = strpos($newString, ' ');
 $getFirstWord = ($getFirstSpace === false) ? $newString : substr($newString, 0, $getFirstSpace);
 
  echo $getFirstWord; // Output: Hello
?>
5. PHP get first word from string using strstr() function

The strstr() function is used to search the first occurrence of a string inside another string. The function is case-sensitive.

Syntax:
strstr($string, $search, $before)
<?php

 $newString = "Hello How are you";
 $getFirstWord = strstr($newString, ' ', true);
 
 echo $getFirstWord; // Output: Hello
 
?>

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *