0

I have data for example

8789 WWW xxx 8739

and if the value like this, the value still 786-456 not 786

786-456

I want to get numeric before string character, how to do that?

the result should be

8789

786-456

here is the code that I have made

$string = '123 home/cat1/subcat2/';
$first = strtok($string, "/^[a-zA-Z]");
echo $first;

the result that I want should be

123

1
  • 4
    Have you tried anything? We're glad to help you sort any issues out with your existing code, but we're not here to do all the work for you. Commented Aug 27, 2019 at 14:49

1 Answer 1

4

You can simply cast it into an int, which will convert as much as it can before encountering a non-int character.

$str="8789 WWW xxx 8739";
echo (int)$str;//outputs 8789
Sign up to request clarification or add additional context in comments.

3 Comments

I'm not a fan of abusing behaviours like this, I hope that at some point PHP starts creating some form of error/warning when people just cast things like this to an int and not do a 'proper' conversion.
@Dimi thanks for your help, but how if I want to keep the value with 234-897, so the value is still 234-897 not 234?
@silviazulinka I am already getting flak for giving out answers to low-effort questions but... depending on how your data is structured you can either do strtok($str,' ');, which will get everything before first empty space or do this regex [0-9\-]+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.