physaux Posted October 16, 2009 Share Posted October 16, 2009 I am having problems splitting up a string.. I am going to be having a value, $inputstring. Examples follow the following pattern: support1at2set support3at9set support2at7set xtra8set master4set.. meaning: it will always be "$text"."number"."set" OR "$text"."number"."$text2"."number"."set" How can i split up the string so that i can extract it into parts, variables? Example: support3at4set ---> $firststring="support", $firstnumber=3, $secondstring="at", $secondnumber=4, $thirdstring="set" i cant figure it out, anyone knows how to do this? Link to comment https://forums.phpfreaks.com/topic/177968-solved-splitting-a-string-by-textnumber-ex-djk44jkasd32sd-djk44jkasd32sd-how/ Share on other sites More sharing options...
thebadbad Posted October 16, 2009 Share Posted October 16, 2009 You can use something like <?php $str = 'djk44jkasd32sd'; $parts = preg_split('~([0-9]+)~', $str, null, PREG_SPLIT_DELIM_CAPTURE); echo '<pre>' . print_r($parts, true) . '</pre>'; ?> Link to comment https://forums.phpfreaks.com/topic/177968-solved-splitting-a-string-by-textnumber-ex-djk44jkasd32sd-djk44jkasd32sd-how/#findComment-938352 Share on other sites More sharing options...
simshaun Posted October 16, 2009 Share Posted October 16, 2009 Well, a solution is posted, but I wasted my time coming up with this so I shall post it anyway <?php $strings = array( 'support1at2set' ,'support3at9set' ,'support2at7set' ,'xtra8set' ,'master4set' ,'nomatch' ); foreach ($strings AS $string) { preg_match('/([A-Z]+)(?[0-9])at([0-9])|([0-9]))set/i', $string, $matches); if (count($matches) > 0) { $firstString = $matches[1]; $firstNumber = isset($matches[4]) ? $matches[4] : $matches[2]; $secondString = 'at'; // not needed $secondNumber = $matches[3] == '' ? NULL : $matches[3]; $thirdString = 'set'; // not needed echo "<pre>"; echo 'First string: '. $firstString .PHP_EOL; echo 'First number: '. $firstNumber .PHP_EOL; echo 'Second string: '. $secondString .PHP_EOL; echo 'Second number: '. $secondNumber .PHP_EOL; echo 'Third string: '. $thirdString .PHP_EOL; echo "</pre>"; } } Link to comment https://forums.phpfreaks.com/topic/177968-solved-splitting-a-string-by-textnumber-ex-djk44jkasd32sd-djk44jkasd32sd-how/#findComment-938353 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.