pino
pino

Reputation: 164

PHP preg_replace find a word in string and remove other characters

I am trying to remove from a string all characters that do not match to a list of words.

my list of words could be:

a string can look like this:

my result should look like this:

my approach:

preg_replace('/(person|animal)/i', '', '123-ea-person.jpg')

output:
123-ea-.jpg

expected output:
person

How can I reverse the pattern to get the result?

Upvotes: 0

Views: 394

Answers (1)

user3783243
user3783243

Reputation: 5224

strtolower with PCRE verbs could achieve your goal:

strtolower(preg_replace('/(?:person|animal)(*SKIP)(*FAIL)|./i', '', '123-ea-person.jpg 456456-on-Person.jpg a-animal-dog.png'));

with this approach a person or animal match would be skipped, all other matches would be replaced with nothing.

https://3v4l.org/pZ9YC

Upvotes: 3

Related Questions