DiegoP.
DiegoP.

Reputation: 45737

Need to remove everything that is after a letter with PHP

I have this link: http://www.youtube.com/e/fIL7Nnlw1LI&feature=related

I need a way in PHP to completely remove everything that is after EACH & in the link.

So it will become : http://www.youtube.com/watch?v=fIL7Nnlw1LI

Attention it could have more than one &

Everything after EACH &, & included, must be deleted from the string

How can I do it in PHP?

Upvotes: 0

Views: 1692

Answers (6)

Pelshoff
Pelshoff

Reputation: 1464

$url = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related";
$ampPos = strpos($var, '&');
if ($ampPos !== false)
{
   $url = substr($url, 0, $ampPos);
}

Don't use explode, regexp or any other greedy algorithm, it's a waste of resources.

EDIT (Added performance information):

In the preg_match documentation: http://www.php.net/manual/en/function.preg-match.php

Tested explode myself with the following code:

$url        = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related&bla=foo&test=bar";

$time1      = microtime(true);
for ($i = 0; $i < 1000000; $i++)
{
    explode("&", $url);
    $url    = $url[0];
}
$time2      = microtime(true);
echo ($time2 - $time1) . "\n";

$time1      = microtime(true);
for ($i = 0; $i < 1000000; $i++)
{
    $ampPos = strpos($url, "&");
    if ($ampPos !== false)
        $url = substr($url, 0, $ampPos);

}
$time2      = microtime(true);
echo ($time2 - $time1) . "\n";

Gave the following result:

2.47602891922
2.0289251804352

Upvotes: 1

Cybercartel
Cybercartel

Reputation: 12592

You can use the explode function () to split the string. $url = explode ( "&", $needle ) and then get the first array element.

Upvotes: 0

RiaD
RiaD

Reputation: 47620

As I wrote in rpevious your question you can use this 1-line script:

$str = strtok($str,'&');

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477130

You can combine strpos with substr:

$spos = strpos($s, "&");
$initial_string = $spos ? substr($s, 0, $spos) : $s;

Upvotes: 1

Toby Allen
Toby Allen

Reputation: 11213

Look at the strpos function, that will give you where the first occurance of a character - in your case & is in a string. From that you can use substr to retrieve the piece of the string you want.

Upvotes: 0

Pheonix
Pheonix

Reputation: 6052

You can do this ::

$var = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related";

$url = explode("&", $var);
$url = $url[0]; //URL is now what you want, the part before First "&"

Upvotes: 3

Related Questions