Skip to content

All topics  /  PHP

PHP Get First Word from String Example

PHP ·

Hi Dev,

This tutorial is focused on php get first word from string example. I’m going to show you about how to get first word from string in php?. I would like to share with you get first word from string in php example. you'll learn how to use function to get first word from string in php? .

There are tow example to get First word from strings in PHP. in this example, we will use to strtok() and preg_match() function to remove First word. so Let's both the following example with output.

Example 1: Get First Word from String


index.php

<?php  	

   
   $str = "Welcome to Nicesnippets.com";

  
   //Get first word of a string
   $result = strtok($str, " ");

   
   echo $result; 

   
?>

Output:

Welcome

Example 2: Get First Word from String

index.php

<?php    

   
   $str = 'Hello all Student';

     
   //Get first word of a string
   preg_match('/\b\w+\b/i', $str, $result); 

     
   echo $result[0];

   
?>

Output:

Hello

I hope it could help you...