John Davidson

php - Regular expression for highlighting numbers between words

0 comments
Message:


Site users enter numbers in different ways, example:


from 8 000 packs
432534534
from 344454 packs
45054 packs
04 555
434654
54 564 packs

I am looking for a regular expression with which I could highlight words before digits (if there are any), digits in any format and words after (if there are any). It is advisable to exclude spaces.


Now I have such a design, but it does not work correctly.


(^[0-9|a-zA-Z].*?)\s([0-9].*?)\s([a-zA-Z]*$)

The main purpose of this is to put the strings in order, bring them to the same form, format them in PHP digit format, etc.


As a result, I need to get the text before the digits, the digits themselves and the text after them into the variables separately.


$before = 'from';
$num = '8000';
$after = 'packs';

Thank you for any help in this matter)



My Answer:
You can use the following regular expression to achieve the desired result:

php
$pattern = '/([a-zA-Z]+)\s*([0-9]+)\s*([a-zA-Z]+)/';
$string = 'from 8 000 packs';

if (preg_match($pattern, $string, $matches)) {
$before = $matches[1];
$num = $matches[2];
$after = $matches[3];

echo "Before: $before\n";
echo "Number: $num\n";
echo "After: $after\n";
}


This regular expression will match a sequence of letters followed by a sequence of numbers followed by another sequence of letters, with optional spaces in between. You can then extract the matched groups into separate variables for further processing.

Rate this post

5 of 5 based on 1112 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us