开发者

php preg_replace - replace part of social

I want to find any pattern matching: ###-##-####

and replace the ###-##, with ***-**

but leave the -####

I tried this below, but nothing is being replaced at all.

preg_replace('/(^[\d]{3})(-)([\d]{2})(-[\d]{4}$)/','\2\4',$myText);

Any help is appreciated


Update, here is my entire code string as it currently stands, after trying a few of the suggestions below. I am comparing the second echo output to the first... and the social numbers all remain the same.

Also, as it was mentioned below, my string does contain more than just a social... it is thousands of characters long. which i think is my real issue. Sorry if i didnt clear that up in the beginning.

    //Make the CSC credit report request.
    $strCscResponse = $Csc->makeRequest($strFixedFormatRecord);

    echo "<br/><br/><pre>" . $strCscResponse  . "</pre><br/><br/>";

    $strCscResponse = str_replace("!", " ", $strCscResponse);

    $strCscResponse = preg_replace('/^\d{3}-\d{2}(-\d{4})$/','***-**$1',$strCscResponse);

    echo "<br/><br/><pre>" . $strCscResponse  . "</pre><br/><br/>";

update

I'd like to mark all the answers and "the answer" just because i didnt clarify the string has more than just a social in it. thank you 开发者_Python百科for the help with this issue, embarrisingly enough it has been driving me wild for a couple days now.


There is one possible problem: you might not be matching the right string (if you are trying to find SSNs buried in a large block of text) - the ^ and $ anchors will only match beginning of string (or sometimes beginning of line) - if this is not what you want, but instead you want to find SSNs in a long string, you need to get rid of those anchors.

The other problem, potentially, is that you seem to want to replace things with asterisks, but you do not include asterisks in your replacement expression. you need to use a replacement expression like

`***-**\4`


Try this regex:

(\d{3})(-)(\d{2})(-\d{4})


Try this:

preg_replace('/^\d{3}-\d{2}(-\d{4})$/','***-**$1',$myText);


  1. you have ^ and $ in your pattern, but I see no m modifier, so this will only match if ###-##-#### is the entire string.
  2. [\d] can be shortened to \d
  3. your \2\4 will leave --####, if you wanted *-#### you can simply have *\4
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜