473,800 Members | 2,227 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

preg_match digits?

What is the most efficient way of extracting the first two digits in a
string?

The following is wrong for me, because it only gives me the first
instance of two digits together:

$string = ujdk3ca94abc
preg_match("/\d{2}/",$string,$resu lt);
echo "$result[0]";
//prints 94. However, the result I am looking for is 39

Here's another example:
$string = 'abc 8a bc abc934';
//desired result = 89

Thank you.

Jul 17 '05
14 7184
On 1 Jun 2004 22:33:10 GMT, Tim Van Wassenhove <eu**@pi.be> wrote:
In article <40************ ***@nospamun8no spam.com>, Westcoast Sheri wrote:
Tim Van Wassenhove wrote:
1-) It works.
2-) I presume it's more efficient than using regular expressions.
Up to you proove me wrong :D
Answer:

<?php
$string = 'a 20adiidkk4kidid 39399399dkkdkkk dk';
$dig = substr(preg_rep lace("/\D/",'',$string),0 ,2);
echo $dig;
?>

Takes .000027 to run.


Feel free to run the following script a few times ;)
test1 always had a smaller execution time than test2 when i tried....


Actually, there's a bug here...
$start = microtime();
foreach($strin gs as $string) {
test1($string,2 );
}
$end = microtime();
echo '<br>total: ' . ($end - start);

^

Missing $.

Notice: Use of undefined constant start - assumed 'start'

Minus isn't defined on strings, so it'll cast 'start' to a numeric type. A
string with no numeric characters evaluates to zero when cast to a numeric
type. microtime() returns a string in the following format:

<microseconds past second> <unix timestamp>

... with a space in between.

Casting that to a numeric type evaluates to the first numeric part, up to the
space. So you end up with microseconds past the second, minus zero.

Unfortunately this bears no relationship to actual execution time :-(

Suprisingly, after fixing the bug, the preg_replace method turns out about 3x
faster than the loop.

$start = microtime(true) ;
foreach($string s as $string) {
test1($string,2 );
}
$end = microtime(true) ;
echo '<br>total: ' . ($t1 = $end - $start);

$start = microtime(true) ;
foreach($string s as $string) {
test2($string);
}
$end = microtime(true) ;
echo '<br>total: ' . ($t2 = $end - $start);
echo '<br> t1/t2 = ' . round($t1/$t2, 4) . 'x';
total: 0.004275
total: 0.001488
t1/t2 = 2.873x

--
Andy Hassall <an**@andyh.co. uk> / Space: disk usage analysis tool
http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space
Jul 17 '05 #11
In article <fk************ *************** *****@4ax.com>, Andy Hassall wrote:
Suprisingly, after fixing the bug, the preg_replace method turns out about 3x
faster than the loop.


*blush* Now, that changes my vision on regular expressions being "slow".
--
Tim Van Wassenhove <http://home.mysth.be/~timvw/contact.php>
Jul 17 '05 #12
Matthias Esken wrote:
... and you're my god. :-)


LOL

I respectfully ask you to choose better gods ...
<OT LEVEL="EXTREMEL Y HIGH">
Like no god at all
</OT>

--
USENET would be a better place if everybody read: : mail address :
http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
http://www.expita.com/nomime.html : to 10K bytes :
Jul 17 '05 #13
Tim Van Wassenhove wrote:
In article <fk************ *************** *****@4ax.com>, Andy Hassall wrote:
Suprisingly, after fixing the bug, the preg_replace method turns out about 3x
faster than the loop.


*blush* Now, that changes my vision on regular expressions being "slow".


*giggle* nya nya nyaaaa nya
Jul 17 '05 #14
On 1 Jun 2004 22:55:58 GMT, Tim Van Wassenhove <eu**@pi.be> wrote:
In article <fk************ *************** *****@4ax.com>, Andy Hassall wrote:
Suprisingly, after fixing the bug, the preg_replace method turns out about 3x
faster than the loop.


*blush* Now, that changes my vision on regular expressions being "slow".


Wasn't the result I was expecting, either. Although I can see reasons for it,
e.g. PCRE is all compiled from C, whereas the loop is all PHP so there's more
overhead.

Given the equivalent loop and PCRE regex both in C, I'd have thought the loop
would win hands down.

--
Andy Hassall <an**@andyh.co. uk> / Space: disk usage analysis tool
http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space
Jul 17 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4246
by: fartsniff | last post by:
hello all, here is a preg_match routine that i am using. basically, $image is set in some code above, and it can be either st-1.gif or sb-1.gif (actually it randomly picks them from about 100 gifs). then it processes them based off of which image type it selected, either the st- 's or the sb- 's.
2
4697
by: Han | last post by:
I'm wondering if someone can explain why the following works with preg_match_all, but not preg_match: $html = "product=3456789&amp;" preg_match_all ("|product=(\d{5,10})&amp;|i", $html, $out); $out = 3456789 preg_match ("|product=(\d{5,10})&amp;|i", $html, $out);
6
1742
by: lkrubner | last post by:
I apologize for my igorance of Regex. I can't get this function to work. It gives the following error message. function checkForFloatingPoint($input=false) { $pattern = "?(*\.+|+)"; $match = preg_match (pattern, subject); echo "The match is: $match "; return $match;
5
7556
by: Mark Woodward | last post by:
Hi all, I'm trying to validate text in a HTML input field. How do I *allow* a single quote? // catch any nasty characters (eg !@#$%^&*()/\) $match = '/^+$/'; $valid_srch = preg_match($match, $res_description); if (!$valid_srch) { ...
6
10252
by: mantrid | last post by:
Hello Found this piece of code using preg_match to check file types during upload of files. $allowed_file_types = "(jpg|jpeg|gif|bmp|png)"; preg_match("/\." . $allowed_file_types . "$/i", $_FILES) I understand the basic preg_match but am confused as to how the string pattern part is working i.e. "/\." . $allowed_file_types . "$/i"
2
1951
by: David | last post by:
Help how can I force the variable to start with a character. I dont want it to start with a number???? function alphanumeric($alphanumeric_field) { if(!preg_match("/+$/",$alphanumeric_field)) return TRUE;
2
4257
by: JanDoggen | last post by:
function vldLicense($lic) { echo "called with lic: ". $lic . "<br>"; echo preg_match('', $lic) . "<br>"; if (preg_match('{4}-{4}-{4}-{4}', $lic) == 0) return false; return true; } gives me:
13
5376
by: chadsspameateremail | last post by:
I might have found a problem with how preg_match works though I'm not sure. Lets say you have a regular expression that you want to match a string of numbers. You might write the code like this: preg_match( '/^+$/', $TestString ); OK everything seems fine. However, did you know if you pass the following to preg_match: "12345\n" it will return that a match occurred?!? Even though the newline is not a valid character in our regular...
8
4002
by: Thomas Mlynarczyk | last post by:
Hello, I want to split a given string into tokens which are defined by regexes: // example tokens - a bit more complex in real $tokens = array( 'NUMBER' ='~^\d+~', 'NAME' ='~^+~', 'ANY' ='~^.~' ); // make sure there is always a match
0
9551
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10505
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10033
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7576
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5471
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.