[英]Regular expression for getting parts of a string
我想用空白替換“10 小時后”或“10 小時后”...... $task_modified 變量應該只打印“提醒我做某事”但是它打印的當前代碼是“提醒我做某事”
字符串中的“s”不是必需的......它的發生是因為正則表達式。 "/after\\s(\\d+)\\shour/"
無論是 1 小時還是 10 小時,我都不需要額外的“s”
<?php
$task = "remind me to do something after 10 hours";
if (preg_match("/after\s(\d+)\shour/", $task, $matches) === 1) {
$hour_after = $matches[1];
$time_24hr = date('H:i:s',strtotime("+".$hour_after." hours"));
$task_modified = str_replace($matches[0],"",$task_modified);
}
這是我嘗試過的......但不起作用:
/after\s(\d+)\s[hour|hours]/
您可以使用POSITIVE LOOKAHEAD實現這一點
$task = "remind me to do something after 10 hours";
preg_match('/(.*)(?=\safter\s(\d+)\s)/mui', $task, $matches);
echo $matches[1]; // remind me to do something
echo $matches[2]; // 10
您可以使用preg_replace而不用環顧:
\h+after\h+\d+\h+hours?$
解釋
\\h+after\\h+
匹配after
1+之間的水平空白字符\\d+\\h+
匹配 1+ 個數字和 1+ 個水平空白字符hours?
使用可選的s
匹配hour
$
字符串結尾$re = '/\h+after\h+\d+\h+hours?$/m';
$task = 'remind me to do something after 10 hours';
$task_modified = preg_replace($re, '', $task);
echo $task_modified;
輸出
remind me to do something
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.