简体   繁体   中英

php advanced search in strings

i'm new to php and maybe this question has been asked before but i don't know what to search for specifically anyway here's the question

if i had a string like

   $adam = "this is a very long long string in here and has a lot of words";

i want to search inside this string for the first occurrence of the word "long" and the word "here"

then select them with everything in between, and store it in a new string

so the result should be

 $new_string = "long long string in here"

and by the way i wouldn't know the length of the string and the contents, all what i know is that it has the word "long" and the word "here" and i want them with the words in between..

Use these functions to do it:

  • strpos() - use it to search words in your string
  • substr() - use it to "cut" your string
  • strlen() - use it to get string length

find position of 'long' and 'word' , and cut your string using substr .

Simple strpos , substr , strlen will do the trick

Your code might look like this

$adam = "this is a very long long string in here and has a lot of words";
$word1="long";
$word2="here";

$first = strpos($adam, $word1);
$second = strpos($adam, $word2);

if ($first < $second) {
    $result = substr($adam, $first, $second + strlen($word2) - $first);
}

echo $result;

Here is a working example

Here is your script, ready for copy-paste ;)

$begin=stripos($adam,"long");  //find the 1st position of the word "long"
$end=strripos($adam,"here")+4; //find the last position of the word "here" + 4 caraters of "here"
$length=$end-$begin;
$your_string=substr($adam,$begin,$length);

Here's a way of doing that with regular expressions:

$string = "this is a very long long string in here and has a lot of words";
$first = "long";
$last = "here";

$matches = array();

preg_match('%'.preg_quote($first).'.+'.preg_quote($last).'%', $string, $matches);
print $matches[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM