簡體   English   中英

PHP的正則表達式似乎無法正常工作

[英]php regex doesn't seem to work as expected

串:

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

碼:

$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... 

我已經在外部測試了正則表達式,並且可以正常工作。 我想拆分/the-string-i-want-to-get/字符串。 我究竟做錯了什么?

我不會使用正則表達式。 在這種情況下,最好使用parse_url和一些其他輔助工具,例如trimexplode

<?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
用正則表達式分割字符串。 用正則表達式分割給定的字符串。

您的$url將被日期分割。 那不是您需要做的方式:

<?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);

您將獲得兩個元素的數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM