简体   繁体   中英

php - preg_replace to highlight formatted phone numbers

I'm having a hard time trying to highlight a search result for a formatted phone number.

$search_txt='5678'; // user generated (can be anything)
$phone_number='(123) 456-7890'; // always in this format

I'm trying this to get the highlighted string:

$highlighted = preg_replace('#'. preg_quote($search_txt) .'#i', '<span style="background-color:#ff0;">\\0</span>', $phone_number);

The $search_txt could be anything. "7890" works, "456-7890", works, but "5678" doesn't work due to the "-" in $phone_number .

I've also tried stripping the format of $phone_number (ie "1234567890"), but if they enter alpha characters "56-78", I have the same issue.

If I strip both $phone_number ("1234567890") and $search_txt ("5678"), the highlighting works and returns 1234<span style="background-color:#ff0;">5678</span>90 , but I don't know how to re-introduce the formatting with the highlight code in the string.

The final string needs to be a phone number format "(123) 456-7890" with highlighting HTML included.

Option #1: Can I format a phone number while ignoring HTML tags within the number?

ie 1234<span style="background-color:#ff0;">5678</span>90

becomes (123) 4<span style="background-color:#ff0;">56-78</span>90

Option #2: Can I ignore the alpha characters in $phone_number when matching, but include them in the replaced string?

ie "5678" would match "(123) 456-7890"

and return (123) 4<span style="background-color:#ff0;">56-78</span>90 .

Assuming your tags have no numeric values as a clear example:

$phone = "1234<span>5678</span>90"; $pattern = '/(\\D*\\d\\D*\\d\\D*\\d)(\\D*\\d\\D*\\d\\D*\\d)(\\D*\\d\\D*\\d\\D*\\d\\D*\\d\\D*)/'; $replace = '($1) $2-$3'; echo "\\n\\n".preg_replace($pattern, $replace, $phone);

produces:

(123) 4<span>56-78</span>90

basically I'm capturing zero-or-more of non-numeric values before each digit and once after the last. This assumes you have reduced both the search string and the target phone number to simple number strings ("4567" and "1234567890") and then performed your search-and-replace to place the HTML tags.

If you must have numbers in your HTML tags, then you must replace \\D with something like <[^>]*>.

$pattern = '/((?:<[^>]*>)*\\d(?:<[^>]*>)*\\d(?:<[^>]*>)*\\d)...

The (?:...) construct groups items without capturing them. Use the {} construct to add a bit of elegance and you have:

$pattern = '/((?:(?:<[^>]*>)*\\d){3})((?:(?:<[^>]*>)*\\d){3})((?:(?:<[^>]*>)*\\d){4}(?:<[^>]*>)*)/';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM