1

I'm new to PHP.

I'm trying to search through an array of data, and match any item that contains a partial string

EX: if user inputs "oh" the search will find any item containing "oh", so the item could be John.

I have this so far, doesn't match anything

if(isset($_POST['firstName'])){
    for($i = 0 ; $i<count($studentInfo);$i++){
        if(strpos($firstName,$studentInfo[$i][2]))

of course there is other code to do something once the item is found. I've seen a lot of substr methods, and STRPOS functions, I just can't figure out how to make it work with my code.

2 Answers 2

2

Edit: Looking closer at your question, it seems as though you are searching for matches within the values of an array. There's something similar to preg_match() for this called preg_grep().

$arrMatchingValues = preg_grep("/^findme/", $array);

Take a look at preg_match(). Using some sample code from that page:

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

$subject is what you want to search. $pattern is the regex pattern that you'd like to match against.

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

Comments

0

You will want to use a regular expression. In your specific case, you should loop through the array, and for each item, use preg_match (as detailed in the linked article). Any matched items should be added to another array, or you can do whatever you want with it.

2 Comments

I'm trying to make this preg_match work with my code, would this go inside the second if loop?
As per PHP [php.net/manual/en/function.preg-match.php]: Tip Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

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.