Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all characters after a specific character [duplicate]

Can anyone tell me how to remove characters after ? in php. I have a string test?q=new and I need to remove the characters from the ? to the end of the string.

like image 654
Anish Avatar asked Feb 16 '12 17:02

Anish


People also ask

How do I remove duplicates from selectively in Excel?

In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.

How do I delete duplicate text in the same cell?

Select a range of cells from which you want to remove repeated text. Press Alt + F8 to open the Macro dialog box. In the list of macros, select RemoveDupeWords2. Click Run.


3 Answers

Shortest one:

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

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

echo strtok('test?=new', '?').'?';
like image 151
Rok Kralj Avatar answered Oct 23 '22 00:10

Rok Kralj


You could always try using preg_replace() as well:

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

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

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

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

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

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

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

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

Array
(
    [test?q] => new
)

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

Array
(
    [q] => new
)
like image 20
summea Avatar answered Oct 22 '22 23:10

summea


Why not:

$pos = strpos($str, '?'); // ? position
$str = substr($str, 0, $pos);
like image 35
Luchian Grigore Avatar answered Oct 23 '22 01:10

Luchian Grigore