chiprivers Posted March 19, 2007 Share Posted March 19, 2007 I think this is probably a regular expression task but I am not too sure how to implement it! I need to seperate a string into three new strings. The original string will be an int, followed by slash and another in then there may be some letters. I would like this to be seperated into the three seperate strings like this: $string = "7/2JF"; $x = 7; $y = 2; $z = "JF"; or another exxample: $string = "3/1"; $x = 3; $y = 1; $z = ""; Any help much appreciated ;0) Quote Link to comment Share on other sites More sharing options...
per1os Posted March 19, 2007 Share Posted March 19, 2007 Yep, REGEX would be the way to go. http://www.phpfreaks.com/forums/index.php/board,43.0.html Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted March 19, 2007 Share Posted March 19, 2007 Something like this: <?php $string = "7/2"; preg_match("#([\d]+)/([\d])([A-Z]+){0,}#", $string, $matches); echo '<pre>' . print_r($matches, true) . '</pre>'; echo ' x = ' . $matches[1] . '<br /> y = ' . $matches[2] . '<br /> z = ' . (empty($matches[3]) ? 'N/A' : $matches[3]); ?> Quote Link to comment Share on other sites More sharing options...
effigy Posted March 19, 2007 Share Posted March 19, 2007 <pre> <?php $string = '7/2JF'; $data = preg_split('%(?:/|(?<=\d))%', $string); print_r($data); ?> </pre> Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted March 19, 2007 Share Posted March 19, 2007 Umm, you can clearly see who's a master in regex here. Quote Link to comment Share on other sites More sharing options...
chiprivers Posted March 19, 2007 Author Share Posted March 19, 2007 <pre> <?php $string = '7/2JF'; $data = preg_split('%(?:/|(?<=\d))%', $string); print_r($data); ?> </pre> Thanks for help, this works fine for single digit ints but the ints before and after the slash may be two or three digits and at the moment it is creating a new array entry for each digit. Quote Link to comment Share on other sites More sharing options...
effigy Posted March 19, 2007 Share Posted March 19, 2007 <pre> <?php $tests = array( '7/2JF', '3/1', '12345/6789', '12345/67890ABC' ); foreach ($tests as $test) { $data = preg_split('%(?:/|(?<=\d)(?=\D|\z))%', $test); print_r($data); } ?> </pre> Quote Link to comment Share on other sites More sharing options...
chiprivers Posted March 19, 2007 Author Share Posted March 19, 2007 <pre> <?php $tests = array( '7/2JF', '3/1', '12345/6789', '12345/67890ABC' ); foreach ($tests as $test) { $data = preg_split('%(?:/|(?<=\d)(?=\D|\z))%', $test); print_r($data); } ?> </pre> perfect, many thanks. I must start learning some regec cause I am sure it would make a lot of other problems I face a lot simpler! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.