Jump to content

Search String


Hellbringer2572

Recommended Posts

Hi,

I need to take a string and search for key elements and then when they are found take a portion of the string and place it in another string for example:

 

$sting = "this is a test of a string";

$searchTerm = "te";

 

$responceString = "test";

 

so i need it to search $string for the term that is set in $searchTerms (te) and then when that variable is found (found in test) take everything till the next space charter and place it into another sting ($responceString)

 

i do know about strpos() but that just returns the location of the string how do i get it to grab the value of the word or is there a better function

 

thanks

Mike

Link to comment
https://forums.phpfreaks.com/topic/189113-search-string/
Share on other sites

This should work for you. Two functions, one to match the first term, the other to match all terms

<?php


$string = "te ten his teen the a test of a string";
$searchTerm = "te";

function get_match($term, $text) {
    $pattern = '%\b'.preg_quote($term, '%').'.*?\b%i';
    if(preg_match($pattern, $text, $matches))
        return $matches[0];
    else
        return false;
}

function get_matches($term, $text) {
    $pattern = '%\b'.preg_quote($term, '%').'.*?\b%i';
    if(preg_match_all($pattern, $text, $matches))
        return $matches[0];
    else
        return false;
    
}
echo get_match($searchTerm, $string);
echo '<pre>'.print_r(get_matches($searchTerm, $string), true).'</pre>';

Link to comment
https://forums.phpfreaks.com/topic/189113-search-string/#findComment-998425
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.