繁体   English   中英

用于获取字符串部分的正则表达式

[英]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
  • $字符串结尾

正则表达式演示| php 演示

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

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