简体   繁体   中英

Regular expression for getting parts of a string

I want to replace "after 10 hour" or "after 10 hours" with blank... $task_modified variable should print only "remind me to do something" however with the current code it prints "remind me to do something s"

"s" in the string is not required.... its happening because of the regular expression. "/after\\s(\\d+)\\shour/"

no matter if its one hour or 10 hours, i dont need that extra "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);
}

this is what i had tried ... but does not work:

/after\s(\d+)\s[hour|hours]/

You may achieve that using 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

You could use preg_replace without lookarounds:

\h+after\h+\d+\h+hours?$

Explanation

  • \\h+after\\h+ Match after between 1+ horizontal whitespace chars
  • \\d+\\h+ Match 1+ digits and 1+ horizontal whitespace chars
  • hours? Match hour with an optional s
  • $ End of string

Regex demo | Php demo

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

Output

remind me to do something

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