user756659
user756659

Reputation: 3512

modifying length of string so certain strings within it count as 1

Can't seem to figure out how to do this one. Given a string I want to return the length of that string... simple enough, but I also want an array of 'search' strings within it to only count as one.

$string = 'this is [Enter]a test example of [Enter]something.';

//this can contain any number of different strings
$replace = array(
    '[Alt]',
    '[Backspace]',
    '[Ctrl]',
    '[Del]',
    '[Down]',
    '[End]',
    '[Enter]'
);

expected output for the above would be :

$string = 'this is [Enter]a test example of [Enter]something.';

// would be 50
$norm_length = strlen($string);

//where all [x]'s in above array count as 1
$length = 38;

Upvotes: 0

Views: 38

Answers (3)

beingalex
beingalex

Reputation: 2476

From your question I think you're asking for a string's characters to be counted but remove the search "term" (words surrounded by square brackets) and count those as 1. Thus giving the character count and adding one for each search term found.

$string = 'this is [Enter]a test example of [Enter]something.';
$originalLength = strlen($string);

echo 'The original length is: ' . $originalLength . '<br />';

//this can contain any number of different strings
$replace = array(
    '[Alt]',
    '[Backspace]',
    '[Ctrl]',
    '[Del]',
    '[Down]',
    '[End]',
    '[Enter]'
);

preg_match_all("/\[([^\]]+)\]/", $string, $searchterms);

echo 'Found:';

var_dump($searchterms[0]);

$newLength = $originalLength;

foreach($searchterms[0] as $term) {
    var_dump(strlen($term));
    $newLength = $newLength - strlen($term) + 1;
}

echo 'New length (without brackets) is';

var_dump($newLength);

Upvotes: -1

Ibrahim AshShohail
Ibrahim AshShohail

Reputation: 2202

I would use a regex to replace any [*] with a space.

$replace = array(
    '/\[Alt\]/',
    '/\[Backspace\]/',
    '/\[Ctrl\]/',
    '/\[Del\]/',
    '/\[Down\]/',
    '/\[End\]/',
    '/\[Enter\]/',
);
$string = preg_replace($replace, ' ', $string);
echo strlen($string);

Upvotes: 0

dognose
dognose

Reputation: 20909

Simple replace every of your keywords with a character of length one:

$string = 'this is [Enter]a test example of [Enter]something.';

//this can contain any number of different strings
$replace = array(
    '[Alt]',
    '[Backspace]',
    '[Ctrl]',
    '[Del]',
    '[Down]',
    '[End]',
    '[Enter]'
);

echo strlen(str_replace($replace, "_", $string));

(str_replace takes an array as search - no need for regex)

Upvotes: 2

Related Questions