0

I want to get rid of a part of a PHP variable if it exists. But the difficulty is that this part contains a dynamic element (numbers), which are always different. And the part that remains is not always the same length in words.

$string = "This is example one 10(+) t/m 16 person";

$string = "This is also an example 12(+) t/m 44 person";

$string = "And this is the final example";

The desired results should be:

$string = "This is example one";

$string = "This is also an example";

$string = "And this is the final example";

So it needs to filter out the "*(+) t/m * person" and I need to do a lot of this, so a compact and a clear solution is desirable.

2

2 Answers 2

2
$words = preg_replace('/\d+/', '', $words );

this removes you all the numbers than all is left

$str = '(+) t/m person ';
    $new= preg_replace("~[^a-z0-9:]~i", "", $str); 
    echo '<pre>'.$new.'</pre>';

Take a look here

Sign up to request clarification or add additional context in comments.

1 Comment

I am glad I helped you
0

If all you are doing is removing a string from another string, the most simple way, would be to use str_replace -

http://php.net/manual/en/function.str-replace.php

in this way:

str_replace("*(+) t/m * person", "", $string)

This does however rely on you knowing the numbers that go in place of the stars.

A more general solution, which would apply to any problem, could utilise another built in function -

fnmatch - http://php.net/manual/en/function.fnmatch.php

Comments

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.