开发者

Add a caret to a Regex Replacement

I am trying to add a Carat to a Date in php

preg_replace('(/[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{4}\/[0-9]{2}\/[0-9]{2}/)', "/\^${开发者_StackOverflow社区1}/", $FileStream);

So that 2000-01-01 becomes ^2000-01-01; Not working


preg_replace(
  '/([0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{4}\/[0-9]{2}\/[0-9]{2})/' ,
  "^$1" ,
  $FileStream
);

For reference, your solution contained the following mistakes:

  1. When using a variable inside a string, and using curly brackets to contain it, you keep the $ inside the brackets - $varName will work, so will {$varName}, but ${varName} will fail.
  2. With Regular Expressions, you are meant to have matching characters at the start and the end of the pattern you are matching - the Regular Expression Delimiters. That character is meant to be outside of any brackets you are using to capture a segment of the matched text. /(.*)/ will work, but (/.*/) will try and treat the opening bracket as the delimiter and will, therefore, fail. (Plus it will try and find / characters at the start and end of the pattern.)


Try this:

preg_replace('/([0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{4}\/[0-9]{2}\/[0-9]{2})/',
             "^$1", $FileStream); 

Your current regex looks like:

'(/regex/)'

so (and ) are being treated as regex delimiters and / and / are treated as literals.

But what you want is:

'/(regex)/'

so that / acts as delimiter and (..) capture the part of the string matching so that it can be used in the replacement as $1 not ${1} as you've used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜