-2

I have these 2 arrays:

array(
  100 => 'this is some text',
  161 => 'prefix1 : this is some text',
  224 => 'some other text',
  356 => 'prefix2 : some other text',
  // ...
)

and

array(
  0 => 'prefix1',
  1 => 'prefix2',
  // ...
)

The first array should not contain the prefixes, so I would like to identify the errors like this as a result:

array(
  161 => 'prefix1 : this is some text',
  356 => 'prefix2 : some other text',
  // ...
)
3
  • Don't you have any attempt to show us ...? Two nested loops, strpos to check if the current text from the first array starts with the current prefix, and if so, add the text to your error array. Commented May 4, 2022 at 9:39
  • Related: Filter array in PHP using keywords? Commented May 19, 2022 at 2:31
  • @Jib Are your prefix strings "known in advance" or are they supplied by a user (a source other than you)? Are the prefixes always numbers and letters? Are these "prefixes" always at the start of the searched strings in the array? Do we need to make "whole word" matches? In other words, do we need to worry about "prefix1" unintentionally matching "prefix11"? Commented May 19, 2022 at 3:51

1 Answer 1

1

You can use array_filter with str_contains like:

$a = [
  100 => 'this is some text',
  161 => 'prefix1 : this is some text',
  224 => 'some other text',
  356 => 'prefix2 : some other text',
  ];


$b = ['prefix1','prefix2'];

print_r(array_filter($a, function($a) use ($b){
    foreach($b as $pref){
        if(str_contains($a, $pref)){
            return true;
        }
    }
}));

Output:

Array
(
    [161] => prefix1 : this is some text
    [356] => prefix2 : some other text
)

Example:

https://sandbox.onlinephpfunctions.com/c/c55a9

Reference:

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

4 Comments

Check for a prefix would rather warrant str_starts_with than str_contains.
@CBroe Yes also, it still seems the same to me since theoretically the prefix is ​​unique and already preset :)
Yes, but they could have f.e. this is some text prefix1 foo bar as one of their input values. str_contains will find prefix1 in there, but if we are actually looking only for texts that are starting with this value, and not just contain it at any arbitrary position, this would be a "false positive" then.
Yes, I get it, that's why I said theoretically the prefix is ​​unique meaning in the sentence

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.