0

I am trying to generate a regex that allows me to do the following:

I have a string containing several terms, all which are alphanumeric and maybe some of these special characters: +.#

They are separated by a comma as well.

This is kind of how it looks like:

$string = 'Term1,Term2,Term3,Term4'; ... And so on... (around 60 terms)

I want to be able to get each term and assign it to a variable, because I want to employ a second Regex to a long string, for example:

$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';

So pretty much I want to be able to check if any of the terms in the first string are present in the second string.

I watched the following tutorial:

https://www.youtube.com/watch?v=EkluES9Rvak

But I just seem to not be able to come up with something.

Thank you so much for your help in advance!

Cheers!

1 Answer 1

1

You can use array_intersect function after splitting strings into tokens:

$string = 'Term1,Term2,Term3,Term4';
$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';

$arr1 = explode(',', $string);
$arr2 = preg_split('/[,\h]+/', $secondString);

$arr = array_intersect(array_map('strtolower', $arr1), array_map('strtolower', $arr2));
print_r($arr);

Output:

Array
(
    [0] => Term1
    [1] => Term2
)
Sign up to request clarification or add additional context in comments.

2 Comments

is this case sensitive? I want it to be case insensitive (?i)
Thank you so much! It does the job!

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.