Sequenzia
Sequenzia

Reputation: 2381

PHP Parse % left characters of a string

I need to match some strings on 80% of the left characters. I can use len() and then figure out what 80% of that length is and set that as variable. Then I can do substr($var, 0, $len80)

That should select 80% of the string but being that I am in 2 loops and I have to do it on both sides I was hoping for a better way of doing this. Anyone know of a easier and more efficient way of selecting a certain percent of a string?

UPDATE

I ended up doing it like this $a2 = substr($a, 0, (strlen($a) * .80));

Same concept just did not have to set multiple variables.

Upvotes: 2

Views: 290

Answers (1)

Sampson
Sampson

Reputation: 268414

Grabbing the left 80% is pretty trivial:

$string = "This is my string";
$length = strlen($string);

echo substr($string, 0, $length * .8);

To grab 50% from the middle, offset by 25% on the starting position:

$result = substr($string, $length * .25, $length * .5);

// Outputs '...is my s...'
echo "..." . trim($result) . "...";

Demo: http://codepad.org/EZnoo2SZ

Upvotes: 2

Related Questions