0

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.

2
  • 1
    What have you tried? See ask advice, please. Commented Feb 23, 2013 at 20:26
  • i don't know like i said i'm new to php and i don't know what to search for.. i tried regular expressions and it seems not to have the answer and also searched for advanced search which wasn't specific enough.. so? Commented Feb 23, 2013 at 20:33

4 Answers 4

1

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.

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

2 Comments

so just to be clear i have to locate the occurrence of the first word and then the occurrence of the second word by using strpos(); and then create the new string by substr(); but what should i do with strlen()?
Upvoted because Peter provides you with all of the tools you might need to accomplish the task. He doesn't simply give you the solution, which is not what stack overflow is about. You should first attempt a solution and then ask for more clarification.
1

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

Comments

0

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);

Comments

0

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];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.