简体   繁体   中英

php regex doesn't seem to work as expected

String:

https://fakedomain.com/2017/07/01/the-string-i-want-to-get/

Code:

$url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
$out = [];

preg_match('\/\d{4}\/\d{2}\/\d{2}(.*)', $url, $out);

// At this point $out is empty... 

// Also...  I tried this (separately)

$keywords = preg_split("\/\d{4}\/\d{2}\/\d{2}(.*)", $url);
// also $keywords is empty... 

I've tested the regex externally and it works. I want to split out the /the-string-i-want-to-get/ string. What am I doing wrong?

I would not use a regex. In this case it's better to use parse_url and some other helpers like trim and explode .

<?php    
$url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';

$parsed = parse_url($url);
$Xploded = explode('/',trim($parsed['path'],'/'));
print $Xploded[count($Xploded)-1];

// outputs: the-string-i-want-to-get

有一个功能:

echo basename($url);

preg_split
Split string by a regular expression. Split the given string by a regular expression.

Your $url will be split by the dates. That's not the way you need to do:

<?php
  $url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
  $out = [];
  preg_match('/\/\d{4}\/\d{2}\/\d{2}(.*)/', $url, $out); 
  // See here...
  var_dump($out);

You will get an array of two elements:

array(2) {
  [0]=>
  string(37) "/2017/07/01/the-string-i-want-to-get/"
  [1]=>
  string(26) "/the-string-i-want-to-get/"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM