Pj M
Pj M

Reputation: 9

PHP script to remove everything before the first occurrence of a number

What I'm trying to remove all data in a string before a the first occurrence of a number like (1-9) maybe in a function?

example:

$value = removeEverythingBefore($value, '1-10'); 

SO if i have a test like "Hello I want to rule the world in 100 hours or so"

I want this to find the first occurrence of a number which is 1 and delete everything before it.

Leaving me with 100 hours or so.

Upvotes: 0

Views: 1601

Answers (3)

Kamrul Khan
Kamrul Khan

Reputation: 3350

If you want to call the function like you mentioned in your post you can do like the below:

<?php
function removeEverythingBefore($value, $pattern) {
    preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE);
    $initialPosition = $matches[0][1];
    return substr($value, $initialPosition);
}

$value = "Hello I want to rule the world in 100 hours or so";
$value = removeEverythingBefore($value, '/[0-9]/');
echo $value; // prints 100 hours or so

This way you can use the same function to match other patters aswell.

Upvotes: 1

Stefan Vilbrandt
Stefan Vilbrandt

Reputation: 292

you could use strpos to get the index of the first occurence and then substr to get the string beginning from that index. Would be faster/more hardware friendly then regex i believe.

Upvotes: 0

Styphon
Styphon

Reputation: 10447

You can use preg_replace for this with the regex /([a-z\s]*)(?=\d)/i like this:

$string = "Hello I want to rule the world in 100 hours or so";
$newString = preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
echo $newString; // Outputs "100 hours or so"

You can see an it working with this eval.in. If you wanted it in a function you could use this:

function removeEverythingBeforeNumber($string)
{
    return preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
}
$newString = removeEverythingBeforeNumber("Hello I want to rule the world in 100 hours or so");

Upvotes: 0

Related Questions