0

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:

  • person
  • animal

a string can look like this:

  • 123-ea-person.jpg
  • 456456-on-Person.jpg
  • a-animal-dog.png

my result should look like this:

  • person
  • person
  • animal

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?

6
  • 1
    probably a better way, but : 3v4l.org/nvF2V Commented Jan 25, 2023 at 20:00
  • 2
    Solution proposed by @Syscall works preg_replace('/(.*)(person|animal)(.*)/i', '$2$4', '123-ea-person.png'); if you delete extension condition Commented Jan 25, 2023 at 20:11
  • @Juan Yay, this works fine strtolower(preg_replace('/(.*)(person|animal)(.*)/i', '$2', '123-ea-person.jpg 456456-on-Person.jpg a-animal-dog.png')); Commented Jan 25, 2023 at 20:28
  • 2
    How about e.g. preg_match('~\b(person|animal)\b~i', $str, $out) Commented Jan 25, 2023 at 21:02
  • What is the desired result if person or animal occur more than once in the string? Commented Jan 25, 2023 at 23:10

1 Answer 1

3

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

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

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.