Jump to content

[SOLVED] Splitting a string by text&number. Ex djk44jkasd32sd --> djk/44/jkasd/32/sd how?


physaux

Recommended Posts

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?

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>";
}
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.