search

Home  >  Q&A  >  body text

Understand how to extract substrings in PHP

<p>I have a URL in the format </p> <pre class="brush:php;toolbar:false;">$string ='https://test.com/uploads/2023/02/06/1/18413/themes/2725/images/dvd_jacket_pdf/dvd_jacket_20630 .pdf';</pre> <p>I need to extract 2725, which is a topic ID, in the application. Can I do this in PHP using regular expressions? I think the logic should be to extract the characters between the subject string and //. </p> <pre class="brush:php;toolbar:false;">preg_match('#themes/(.d )#', $string, $check);</pre> <p>I also want to add slashes to this regex. </p>
P粉257342166P粉257342166518 days ago546

reply all(1)I'll reply

  • P粉237029457

    P粉2370294572023-08-08 09:33:12

    You don't need to use a slash, and you have an extra dot in the pattern. Just use this:

    $string = 'https://test.com/uploads/2023/02/06/1/18413/themes/2725/images/dvd_jacket_pdf/dvd_jacket_20630.pdf';
    if(preg_match('#themes/(\d+)#', $string, $check))
        echo $check[1]; 

    reply
    0
  • Cancelreply