php preg_replace - replace part of social - php

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

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

Related

How to match 2 unknown letters after a letter in php

i am trying to get this
string = 'Boss S02E06 more string'
i want S02E06 out of the complete string . and if possible split the string there.
Please note that the values after S and E in that keep changing so its not constant .
But im not expert when it comes to it.But i guess its time to start learning.
Thanks guys
try this:
$string = "Boss S02E06 more string";
preg_match(`.*(S\d+E\d+).*`,$string,$match);
echo $match[0];// it will echo S02E06
You would use a Regular Expression. You can learn them here.
PHP has preg_match(), which is what you would use.
The regex to match would be something like S\d+E\d+. If you want the values, use a capturing group.
It's up to you to put all these ideas together to arrive at an answer.

How can this regex by improved? It's hitting the PREG_BACKTRACK_LIMIT_ERROR for PHP on very short text

The following regex:
$common_tlds = 'us|me|com|net|org|ly|be|edu|gov|uk|ca|de|jp|fr|au|ru|ch|it|nl|se|no|es|mil|co';
$regex = '#(?:https?://)?([^.\s]+(?:[^\s.]|[^\s][^\s.])*\.(?:' . $common_tlds . ')[^.\s]*)#i';
used here:
preg_replace($regex,'$1', $text);
Is giving me a PREG_BACKTRACK_LIMIT_ERROR on very short text. One example text is:
Life cant always give you the best shoes,handbags,clothes but it can give you the best creations.
I know, there are better link finding regex online, but I was curious about what in my regex was causing massive backtracking and how I could improve it. Thanks!
Try something like this:
$regex = '#(?:https?://)?([^.\s]+(?:\.[^.\s]+)*\.(?:' . $common_tlds . '))#i';
Comments:
You are seeing catastrophic backtracking - your pattern has too many ways to fail matching the string.
[^.\s]+(?:\.[^.\s]+)* allows only one way of matching the domain, anchoring at dots.
[^.\s]* - Removed from the end, not sure what it suppose to do after the tld. If you want to match domains like .co.il, you may want another dot there: (?:\.[^.\s]+)?
You may want a \b at the start, to avoid matching (google.com.

Positive look ahead regex confusing

I'm building this regex with a positive look ahead in it. Basically it must select all text in the line up to last period that precedes a ":" and add a "|" to the end to delimit it. Some sample text below. I am testing this in gskinner and editpadpro which has full grep regex support apparently so if I could get the answers in that for I'd appreciate it.
The regex below works to a degree but I am unsure if it is correct. Also it falls down if the text contains brackets.
Finally I would like to add another ignore rule like the one that ignores but includes "Co." in the selection. This second ignore rule would ignore but include periods that have a single Capital letter before them. Sample text below too. Thanks for all the help.
^(?:[^|]+\|){3}(.*?)[^(?:Co)]\.(?=[^:]*?\:)
121| Ryan, T.N. |2001. |I like regex. But does it like me (2) 2: 615-631.
122| O' Toole, H.Y. |2004. |(Note on the regex). Pages 90-91 In: Ryan, A. & Toole, B.L. (Editors) Guide to the regex functionality in php. Timmy, Tommy& Stewie, Quohog. * Produced for Family Guy in Quohog.
I don't think I understand what you want to do. But this part [^(?:Co)] is definitely not correct.
With the square brackets you are creating a character class, because of the ^ it is a negated class. That means at this place you don't want to match one of those characters (?:Co), in other words it will match any other character than "?)(:Co".
Update:
I don't think its possible. How should I distinguish between L. Co. or something similar and the end of the sentence?
But I found another error in your regex. The last part (?=[^:]*?\:) should be (?=[^.]*?\:) if you want to match the last dot before the : with your expression it will match on the first dot.
See it here on Regexr
This seems to do what you want.
(.*\.)(?=[^:]*?:)
It quite simply matches all text up to the last full stop that occurs before the colon.

How can I match everything with a PHP regular expression?

How can I match everything with a PHP regular expression? I tried: /[.\r\n]*/, but it isn't working. Any ideas? Thanks.
This is for a method I made for a PHP class to parse e-mails:
public function getHeader($headerName) {
preg_match('/[\r\n]' . $headerName . '[:][ ](.+)[\r\n][^ \t]/Uis', "\n" . ltrim($this->originalMessage), $matches); return preg_replace('/[\r\n]*/', '', $matches[1]);
}
/.*/s (see perl's docs). The s option means (quoting from that URL):
Treat string as single line. (Make . match a newline)
I assume, based on your inclusion of \n and \r above, that you want to match across multiple lines. In this case, use:
/.*/s
(note the explicit /s modifier, that is, change . to match any character whatsoever, even a newline, which it normally would not match.)
See http://www.perl.com/doc/manual/html/pod/perlre.html
Why do you want to match everything? There's no point in using it as a condition because it's always true. If you want to capture the text you don't need a regex to do it because you just use the entire string. If you're trying to get around taint-checking, then shame on you (and ask a separate question about doing that right).
Note that we have a bit of the XY Problem here. You have some task X in mind, and think Y is part of the solution. You ask about Y but never tell us X. It's hard to answer your real question when we don't know what you are trying to do. :)
What about /.*/s?
In a character class ( the [] ), . just means period.
Does /[\.\r\n]+/ do what you want?
This kludge has also worked for me before:
my $abstract_text = /Abstract:([\s\S]+?)\nReferences/m;
It's useful if you want to capture patterns with arbitrary text included or intervening between multiple captures.

replace exact match in php

im new to regular expressions in php.
I have some data in which some of the values are stored as zero(0).What i want to do is to replace them with '-'. I dont know which value will get zero as my database table gets updated daily thats why i have to place that replace thing on all the data.
$r_val=preg_replace('/(0)/','-',$r_val);
The code im using is replacing all the zeroes that it finds for eg. it is even replacing zero from 104.67,giving the output 1-4.56 which is wrong. i want that data where value is exact zero that must be replaced by '-' not every zero that it encounter.
Can anyone please help!!
Example of the values that $r_val is having :-
10.31,
391.05,
113393,
15.31,
1000 etc.
This depends alot on how your data is formatted inside $r_val, but a good place to start would be to try:
$r_val = preg_replace('/(?<!\.)\b0\b(?!\.)/', '-', $r_val);
Where \b is a 0-length character representing the start or end of a 'word'.
Strange as it may sound, but the Perl regex documentation is actually really good for explaining the regex part of the preg_* functions, since Perl is where the functionality is actually implemented.
Again, it would be more than helpful if you could supply an example of what the $r_val string really looks like.
Note that \b matches at word boundaries, which would also turn a string like "0.75" into "-.75". Not a desirable result, I guess.
Whilst the other answer does work, it seems overly complex to me. I think you need only to use the ^ and $ chars either side of 0.
$r_val = preg_replace('/^0+$/', '&#45', $r_val);
^ indicates the regex should match from the beginning of the line.
$ indicates the regex should match to the end of the line.
+ means match this pattern 1 or more times
I altered the minus sign to it's html code equivalent too. Paranoid, yes, but we are dealing with numbers after all, so I though throwing a raw minus sign in there might not be the best idea.
Why not just do this?
if ( $r_val == 0 )
$r_val = '-';
You do not need to use a regex for this. In fact, I'd advise against doing so for performance reasons. The operation above is approximately 20x faster than the regex solution.
Also, the PHP manual advises against using regexes for simple replacements:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().
http://us.php.net/manual/en/function.str-replace.php
Hope that helps!

Categories