View Full Version : question about preg_match
awakener1986
02-23-2010, 10:13 AM
hi
i was told that preg_match can be used to split strings and store them in arrays
how does preg_match actually works?
for example i would like to store this string in an array
$text = '720101-11-5903 (A2037135)';
i want it to be like this
$arr[0] = 720101-11-5903
$arr[1] = A2037135
thanks. help would be much appreciated
james438
02-25-2010, 07:43 PM
Hi,
I am sure there is a better way to do this, but try this:
<?php
$text = '720101-11-5903 (A2037135)';
$text=preg_split('/[^a-zA-Z0-9\-]/',$text);
foreach($text as $key => $value) {
if($value == "") {
unset($text[$key]);
}
}
print_r($text);
?>
preg_match (http://us2.php.net/manual/en/function.preg-match.php) will match what you are looking for and put it into an array. Preg_match is a good way to look for a needle in a haystack of code or text. It is handy in the sense that it will not do anything to the string like preg_split (http://us2.php.net/manual/en/function.preg-split.php) or preg_replace (http://us2.php.net/manual/en/function.preg-replace.php) or whatever, but the problem is that if you want to match more than the first match in your string/variable then you will need to use preg_match_all, which will store all of your matches into a multidimensional array, which can get a bit more complicated.
In your post you said that you wanted to split the string, so I used preg_split.
If it were me I would not use a regular expression at all and would do something like:
<?php
$text = '720101-11-5903 (A2037135)';
$text=str_replace(array('(',')'),'',$text);
$text=explode(' ',$text);
print_r($text);
?>
The reason being that str_replace is simpler and requires a lot less processor power. It is more efficient and much more efficient.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.