How to return particular word in the string ??

Discussion in 'Programming/Scripts' started by Prahlad Makwana, Dec 3, 2019.

  1. Hello, everyone
    I want "Sumit" as output but it returns me empty string.
    I have tried something like this:
    Code:
    <?php
    $email  = '[email protected]';
    $user = strstr($email, 'sumit', true);
    echo $user;
    ?>
    
    Thanks In Advance
     
  2. Harsh Shah

    Harsh Shah Banned

    Hi
    This code will give you null every time you call it because here you have used strstr() function which is a built-in function of php.
    It searches for the first occurrence of a string inside another string and displays the portion of the latter starting from the first occurrence of the former in the latter (before if specified).
    in your code, first parameter of function is the string($email) in which we want to perform search operation which is mandatory.
    second parameter is also a mandatory parameter('sumit') which specifies the string to search for.
    And third parameter(true) is a optional. it specifies a Boolean value. If you set it to true, it returns the part of the string($email) before the first occurrence of Search('sumit') parameter. And if you set it to false, function returns the rest of the string (from the matching point). By default it is false. Read more about this function here: https://www.w3schools.com/php/func_string_strstr.asp

    So here, you want to get output as a 'sumit' but you have passed second parameter as sumit and also set third parameter to true. So in this scenario, function will find string which occurrence before 'sumit'. so it will get null value because there is not any string before 'sumit'.

    So the solution is, you have to pass search string '@gmail.com' or only '@' to second parameter if you want to get output as a 'sumit'. so function will find string which occurrence before search string. and you will get output as 'sumit'. see below code:

    Code:
    <?php
    $email  = '[email protected]';
    $user = strstr($email, '@gmail', true);
    echo $user;
    ?>
    Try this and let me know if have any query. Hope this will help you.
    Thank you.
     

Share This Page