如何在字符串中搜索字符并在该字符后保存带有文本的变量?

I have a string with the following content

http://www.mysite.com/test.php?http://www.anotherwebsite.com

how can i save the second url in a php variable?

i mean, the url after the interrogation mark.

If you had the following

$double_url = 'http://www.mysite.com/test.php?http://www.anotherwebsite.com';

then you could do this

$second_url = substr(strstr($double_url, '?http'), 1);

OR this

$second_url = preg_replace('/.*\?(http.*)/', '$1', $double_url);

OR this

$second_url = substr($double_url, strpos($double_url, '?http')+1);

OR many other approaches that will give you the same result.

I am concerned with using ? as a delimiter between URLs because the ? is a valid and important part of the full URI. For this reason my examples use '?http' instead of just '?' but there are still potential pitfall situations even with '?http'

You're in luck, PHP has functions for that! They are called strpos() and substr() and this is how they work:

$haystack = "http://www.mysite.com/test.php?http://www.anotherwebsite.com";
$needle = "?";
$needle_pos = strpos($haystack,$needle);
$text_after_needle = substr($haystack,$needle_pos+1);

There are actually MANY ways to do this. It can be accomplished with explode() and grabbing the second array element. It could also be done using regular expressions. The above code is just a simple way to search for a character in a string and grab any text after that.

Where:

$url = 'http://www.mysite.com/test.php?http://www.anotherwebsite.com';

Try:

$url2 = end(explode('?',$url));

Then:

echo $url2;

Will be:

http://www.anotherwebsite.com

Try this example.

<?php
$url = "http://www.mysite.com/test.php?http://www.anotherwebsite.com";
$params = parse_url($url);
$otherSite = $params['query'];
echo $otherSite;
?>