Check if a string contains an item in an array

Ask about a PHP problem here.
Post Reply
JelvinJS7
Posts: 341
Joined: Thu May 12, 2011 8:40 pm

Check if a string contains an item in an array

Post by JelvinJS7 »

Ok I feel really lame for asking this. I swear I know this in the back of my mind somewhere. I'm so out of practice :/

So I'm trying to come up with a quick PHP application that can convert a strand of DNA into mRNA and/or mRNA into tRNA (or however that works—I'm not following this unit that well :lol: ). The way it works is you select which nucleic acid it is, and input a sequence, and it outputs the conversion by replacing each base with its corresponding pair.

Anyway, I'm having trouble checking that the inputted sequence contains only legitimate base pairs—A, T, U, G, and C. What I have is an array containing each of those letters, and I'm not quite sure how to check that the string only contains characters existing in the array. Any help (or alternate solutions) would be greatly appreciated!

I should probably focus more on the conversion than the checks… or more importantly, my actual homework. ;) But that's not fun.
ExtremeGaming
Posts: 205
Joined: Mon Jul 09, 2012 11:13 pm

Re: Check if a string contains an item in an array

Post by ExtremeGaming »

Hmm...tricky

Perhaps you could use foreach() along with preg_match()/any other thing that looks for stuff ?
<?php while(!$succeed = try()); ?>
JelvinJS7
Posts: 341
Joined: Thu May 12, 2011 8:40 pm

Re: Check if a string contains an item in an array

Post by JelvinJS7 »

yeah i tried using some code i found online giving that advice. didn't seem to work.
i'm not a fan of RegExp, as I can never understand how to use them or their corresponding functions (ie preg_match)
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Check if a string contains an item in an array

Post by jacek »

So you have a string and an array of letters, you want to check if the string contains anything that is not in that array ? If that is correct I would go for a regex approach instead
if (!preg_match('#^[ATUGC]+$#', $string)){
  // um :(
}
You could probably do it with some combination of the array_* functions too
Image
Post Reply