Skip to content
Advertisement

How Eliminate ? in this string with preg_mach

Hello Have this string

class="_2zACE" href="/tv-shows/521987/s01_e01_the_killings_at_badgers_drift?start=true"

I Use this Regx

preg_match_all('/class="_2zACE" href="(/tv-shows/)(.+?)/(.+?)?start=true"/',$url_pre_series,$url_lote_serie,PREG_SET_ORDER);

The Anwser is this:

Array
(
   
    [0] => class="_2zACE" href="/tv-shows/521987/s01_e01_the_killings_at_badgers_drift?start=true"
    
    [1] => /tv-shows/
    
    [2] => 521987
    
    [3] => s01_e01_the_killings_at_badgers_drift?

)

How I can do for eliminate the last ? in the Array [3], i try difference option but nothing.

Advertisement

Answer

You could place the questionmark outside of the capturing group and as it was part of the previous group which was optional, you could make the question mark itself optional using ??

To match the parts in between, you could also use 2 negated character classes if you want to match 2 parts

class="_2zACE" href="(/tv-shows/)([^/]*)/([^/?]*)???start=true

Regex demo

If you change the delimiter from / to for example ~ you don’t have to escape the backslash.

$url_pre_series = 'class="_2zACE" href="/tv-shows/521987/s01_e01_the_killings_at_badgers_drift?start=true"';
preg_match_all('~class="_2zACE" href="(/tv-shows/)([^/]*)/([^/?]*)???start=true~',$url_pre_series,$url_lote_serie,PREG_SET_ORDER);
print_r($url_lote_serie);

Output

Array
(
    [0] => Array
        (
            [0] => class="_2zACE" href="/tv-shows/521987/s01_e01_the_killings_at_badgers_drift?start=true
            [1] => /tv-shows/
            [2] => 521987
            [3] => s01_e01_the_killings_at_badgers_drift
        )

)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement