Jump to content

[SOLVED] 7/2JF => 7, 2 and JF


chiprivers

Recommended Posts

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)

Link to comment
https://forums.phpfreaks.com/topic/43358-solved-72jf-7-2-and-jf/
Share on other sites

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]);

?>

<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.

<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!

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.