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
https://forums.phpfreaks.com/topic/75256-substr-with-dependent-length-parameter/
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>

 

 

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.

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.

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.