[ACCEPTED]-Remove everything after a character in PHP-php

Accepted answer
Score: 38

Shortest one:

echo strtok('test?=new', '?');

If you want to keep the question 1 mark, the solution is almost the same:

echo strtok('test?=new', '?').'?';
Score: 5

You could always try using preg_replace() as well:

$string = 'test?q=new';
$result = preg_replace("/\?.+/", "", $string);

If, for 12 some reason, you are wanting to keep the 11 ? in the result... you could also do this:

$string = 'test?q=new';
$result = preg_replace("/\?.+/", "?", $string);

(or, you 10 could use a positive look-behind assertion, as 9 @BlueJ774 suggested,) like this:

$result = preg_replace("/(?<=\?).+/", "", $string);

But ideally, and for future reference, if 8 you are working with a query string, you probably will 7 want to use parse_str at some point, like this:

$string = 'test?q=new';
parse_str($string, $output);

Because that will 6 give you an array ($output, in this case,) with 5 which to work with all of the parts of the 4 query string, like this:

Array
(
    [test?q] => new
)

But normally... you 3 would probably just want to be working with 2 the query string by this point... so the 1 output would be more like this:

Array
(
    [q] => new
)
Score: 2

Why not:

$pos = strpos($str, '?'); // ? position
$str = substr($str, 0, $pos);

0

Score: 2

You can do this with a well-written regex, but 5 the much simpler and quicker way to do it 4 is to explode the string on the "?" character, and 3 use the first element in the resulting array.

$str = "test?=new";
$str2 = explode("?", $str);
$use_this = $str2[0];

$use_this[0] will 2 be "test". If you want to add the "?" back, just 1 concatenate:

$use_this = $use_this."?";
Score: 1

Here is one-liner:

$s = strpos($s, '?') !== FALSE ? strtok($s, '?') : $s;

You can test it by the 1 following command-line:

php -r '$s = "123?456"; $s = strpos($s, "?") !== FALSE ? strtok($s, "?") : $s; echo $s;'
Score: 0

substr and strpos

The simplest way to do this is with substr() DOCs and 4 strpos() DOCs.

$string = 'test?=new';
$cut_position = strpos($string, '?') + 1; // remove the +1 if you don't want the ? included
$string = substr($string, 0, $cut_position);

As you can see substr() extracts a sub-string from 3 a string by index and strpos() returns the index 2 of the first instance of the character it 1 is searching for (in this case ?).

Score: 0

Use the strstr function.

<?php
$myString = "test?=new";
$result = strstr($myString, '=', true);

echo $result ;

The third parameter true tells 2 the function to return everything before 1 the first occurrence of the second parameter.

More Related questions