celsowm
celsowm

Reputation: 402

Regex replace in PHP to getting a number or a range after some prefixes

I have some texts with reference to lawsuit pages (folhas "fl. or fls." in portuguese) that I need to replace those numbers for a link (tag a) with an URL like:

"localhost/m-n-i/consultarFolhas/".$page_start."/".$page_end

Text examples:

As you can see some times they use plural (s) even for single pages but for multiple pages they normally use "/" to the separate the range.

I tried this Regex but it is still ineficiente to catch the situations described above:

const REGEX_FOLHAS = '#^.*\bfls?\. (\d+).*$#m';

So is it possible to create a REGEX to get those situations and replace with a hyperlink like this?

Nos termos das <a href='localhost/m-n-i/consultarFolhas/10/44/'> FLS 10/ 44 </a> estão

<a href='localhost/m-n-i/consultarFolhas/53/'>Fl. 53</a>: Considerando a manifestação do Estado, excluam-se os executados

Upvotes: 0

Views: 41

Answers (1)

revo
revo

Reputation: 48741

Your regex is almost what you want but you forgot some patterns and modifiers:

  • Remove anchors and greedy dots (m flag too)
  • Enable case-insensitivity (i flag)
  • Make \. and following space characters optional: \.? *
  • Write an optional pattern for slash separated digits (?:\/ *\d+)?
  • Use capturing groups to extract data

Putting all together:

(?i)\bfls?\.? *(\d+)(?:(/) *(\d+))?

Live demo

PHP code:

preg_replace('~(?i)\bfls?\.? *(\d+)(?:(/) *(\d+))?~', '<a href="localhost/m-n-i/consultarFolhas/$1$2$3">$0</a>');

Upvotes: 1

Related Questions