Jump to content

substr with dependent length parameter


rbragg

Recommended Posts

Is it possible to use substr() to get only the letters displayed after numbers (at the end of a string)? For example:

 

WA-0318a would give me a

SAN-2011Aa would give me Aa

KE-2200Eb would give me Eb

 

So, if $variable = "SAN-2011Aa" then substr($variable, -?). The negative length parameter would be dependent on how many of the ending characters are letters and not numbers. In this case, I would need to dynamically generate 2 (for -2). In the case of "WA-0318a" I would need to dynamically generate 1 (for -1).

 

Is this possible?

Link to comment
Share on other sites

Regular expressions will be the easiest approach:

 

<pre>
<?php 
$tests = array(
	'WA-0318a',
	'SAN-2011Aa',
	'KE-2200Eb'
);
foreach ($tests as $test) {
	echo "<b>$test</b><br>";
	preg_match('/(?<=\d)[a-z]+\z/i', $test, $matches);
	print_r($matches);
	echo '<hr>';
}
?>
</pre>

 

 

Link to comment
Share on other sites

Thanks for your reply. I will only have one string in $variable so I wouldn't start with an array. Also, I wouldn't need ALL of the letters from the string ... only those at the end.

<?php
preg_match('/(?<=\d)[a-z]+\z/i', $variable, $result);
echo $result;
?>

 

This gives me an array of letters. I would like to end up with one string from $variable. In the case of "SAN-2011Aa", I'd like to get "Aa" ... not "A" and "a". Also, I'd like to leave out "SAN".

 

Thanks again.

Link to comment
Share on other sites

If I directly assign that, it works:

 

<pre>
<?php
$hallRoomSpace = 'KE-2200Eb';

preg_match_all('/(?<=\d)[a-z]+(?=(?:\r?\n)|\z)/i', $hallRoomSpace, $matches);
print_r($matches);
echo implode('', $matches[0]);
?>
</pre>

 

And if you're only going to have one sequence in there, you can switch to preg_match.

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.