Home > Software design >  How to get part of string without using substr() function
How to get part of string without using substr() function

Time:10-03

I have a string like this:

$str = "65moneyback";

Now I need to get moneyback from this string and store in a new variable.

So basically I can easily use substr() function to do this, but the problem is, the number at the beginning can be anything else such as 135moneyback or 9moneyback and etc.

Therefore I don't know when the moneyback starts from exactly and what to enter as index for substr() function.

But the moneyback part stays the same always.

So the question is, how to get moneyback from these kinds of string variables properly?

CodePudding user response:

You could use preg_replace:

$str = "65moneyback";
$output = preg_replace("/\d /", "", $str);
echo $output;  // moneyback

The above logic says to replace all digit characters with empty string, which is the same thing as removing all digits.

Fot another regex approach, we could also try using a regex split here:

$str = "65moneyback";
$output = preg_split("/(?<=\d)(?=\D)/", $str)[1];
echo $output;  // moneyback

This version splits the input into the first digits component and second text component, retaining only the latter.

CodePudding user response:

You can also try this:

<?php
    $str = "5moneyback";
    $result = strstr($str, "moneyback");
    echo $result;
?>

CodePudding user response:

I would also go for the regex solution (remove /^\d*/).

Just for completeness: If you want to cut the "PHP Integer"-part from the beginning of the string, you could still do it with substr():

substr($str, strlen((int) $str));
  • Related