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

?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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