1

I'm trying to build a preg replace for numbers in my script.

Let's have this example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Integer lobortis luctus scelerisque. Curabitur 3214567890 dignissim finibus felis,
vitae vehicula ipsum vehicula a. 
Maecenas tincidunt et metus vitae eleifend. Cras tellus eros, placerat 
https://www.facebook.com/groups/123456789123456789/

I have to find a number that it's write on a text source that 99% starts with 3 and it has 10 digits.

I wrote this simple preg_replace

preg_replace('/3[0-9]{6}([0-9]{3})/e', '"Number" . md5("$0") . " " . "["."$1"."]"', data)

because I need to replace that number with md5 and write last 3 digits.

For example if I have 3214567890 I need to get

Number89467086c22e2cee9aae8dbf9c7f7453 [890]

That preg_replace did the work but it has 1 problem.

The problem I found few days ago is that if in source I have a link with a lot of numbers, for example, a facebook link

https://www.facebook.com/groups/123456789123456789/

preg_replace elaborates it too and replace numbers of that link, but I don't need to touch links, I need to convert only separated numbers.

Can anyone help me?

1
  • Did you try adding \s? If all numbers are separated from other text using space characters, that may work. Commented Dec 19, 2016 at 11:38

1 Answer 1

2

You may use word boundaries \b:

'~\b3[0-9]{6}([0-9]{3})\b~'

or lookarounds (?<!\d) and (?!\d) (to match only if not enclosed with other digits):

'~(?<!\d)3[0-9]{6}([0-9]{3})(?!\d)~'

Or, if you want to only match the numbers when enclosed with whitespace symbols, use

'~(?<!\S)3[0-9]{6}([0-9]{3})(?!\S)~'

Then, inside the code, you'd better use preg_replace_callback since /e modifier is deprecated:

preg_replace_callback('~(?<!\d)3[0-9]{6}([0-9]{3})(?!\d)~', function($m) {
     return 'Number' . md5($m[0]) . ' [' . $m[1] . ']';
   }, data);
Sign up to request clarification or add additional context in comments.

2 Comments

It works, but I found another problem: it convert if it found link like this: domain.com/Page/?num=3711436157
Ok, do you want to only match inside whitespaces? Use '~(?<!\S)3[0-9]{6}([0-9]{3})(?!\S)~'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.