caramba
caramba

Reputation: 22480

Remove colon if not between digits

$str = "xxx:'2015-10-09 15:05'";

$patterns[0] = '/:/';
$patterns[1] = '/\'/';
$patterns[2] = '/xxx/';

var_dump( preg_replace($patterns, '', $str) );

This outputs: string(15) "2015-10-09 1505"

But I need string(16) "2015-10-09 15:05"

Upvotes: 0

Views: 83

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

If you know that your input string is:

1) beginning with xxx:'
2) ending with '

and you need everything in between the apostrophes, you may use preg_replace with the /^xxx:'([^']*)'$/ regex:

$str = "xxx:'2015-10-09 15:05'";
var_dump( preg_replace("/^xxx:'([^']*)'$/", '$1', $str) );

See IDEONE demo

Output: string(16) "2015-10-09 15:05".

Or as an alternative, use matching regex:

$str = "xxx:'2015-10-09 15:05'";
if (preg_match("/(?<=')[^']+/", $str, $m)) { 
 var_dump( $m );
}

Here, (?<=')[^']+ will match 1 or more characters other than a single apostrophe ([^']+) right after a single apostrophe ((?<=')).

Upvotes: 4

Related Questions