Ltrim() to trim up till " "

i have

$var = "Cabinet  7N";

and am trying to trim the stufff on the left till the space, so

$var = "7N";

I tried ltrim($var, " "), am i on the right track?

No. Looks like, you need a regular expression. E.g.

preg_match('/^(\d+)(\s+)(\d+)$/', $var, $matches);
$var = $matches[3];

oh, would it work on a variable like

$var = "Cabinet 3";

Yes. I can’t to be absolutelly sure in reg. exps., because format of your string is not clear. Do you always have a prefix 'Cabinet ’ and than the string you would to get or prefix could be different?

Its based on user input, theres always a chance it’ll be Cab 7N if some idiot tries to be funny, So all I want the varfiable to be is 7N

You may not need to use regex. Could you use https://www.php.net/manual/en/function.strrpos.php (roughly, “string reverse position”) to find the space and use that in https://www.php.net/manual/en/function.substr.php to get the substring?

1 Like

Sounds like a case for better validation if the user can enter stuff that they should not.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.