Zaffar Saffee
Zaffar Saffee

Reputation: 6305

Dropping words from a string in php

i have a string

showing 1 - 12 of 324 Results

i want to stip this string like

324 Results

or

324

only

Note that, 324 is figure that will change every time the string is obtained. it may be 2-figures (34), three or 4 figured.

currently i am at success only in droping showing word using code

'str_replace('Showing', '', $s)'

this gives out put as

1 - 12 of 324 Results

how can i use str_replace function to get my purpose? or i should use anyother function of PHP?

Upvotes: 2

Views: 110

Answers (7)

dfsq
dfsq

Reputation: 193301

$results = explode('of', $str);
$results = (int)$results[1];

Upvotes: 0

Sam Arul Raj T
Sam Arul Raj T

Reputation: 1770

Use This So easy

$exampleString = "showing 1 - 12 of 324 Results";
$arrayResult   =explode(" ",$exampleString);

//output will be 324,according to the index the result will change
echo $arrayResult[5];

Upvotes: 1

bizzr3
bizzr3

Reputation: 1955

check this :

$result = "showing 1 - 12 of 324 Results";
$buffer = substr( $result , strpos( $result , "of") + 2 , strlen($result));
//$buffer is : 324 Results

$buffer = explode(" ", $buffer);

// you have to block 1 : $buffer[0] ~ '324' AND 2 : $buffer[1] : 'result'

Upvotes: 0

Hristo Petev
Hristo Petev

Reputation: 309

Alex's answer is good, maybe a regular expression needs more time to understand. You can explode the string and just get the element before the last one.

$arr = explode(' ', 'showing 1 - 12 of 324 Results');
$number = $arr[count($arr)-2];

This way you will get the number of total results. And whenever you want you can add the 'Results' word. Don't forget to trim() the string before the explode() is called.

Upvotes: 0

Logan Serman
Logan Serman

Reputation: 29880

One solution would be to split the strings at " of " and again at " Results".

$temp = explode(' of ', $yourString);
$temp2 = explode(' Results', $temp[1]);
$totalResults = $temp2[0];

You can also use preg_match() as alex suggested, which is a more 'elegant' solution as it is done with one function call but may be difficult to understand if you are not familiar with regex.

Upvotes: 0

anubhava
anubhava

Reputation: 786291

This should work:

preg_replace('~^.*?(\d+\s+Results)$~i', '$1', 'showing 1 - 12 of 324 Results');

OR

preg_match('~\d+\s+Results$~i', 'showing 1 - 12 of 324 Results', $m);
var_dump ( $m[0] );

Upvotes: 1

alex
alex

Reputation: 490647

You could use preg_match().

preg_match('/(?P<results>\d+)\sResults$/', $str, $matches);

CodePad.

Then examine $matches['results'] for the number of results or $matches[0] for the number of results and the ' Results' substring.

Upvotes: 6

Related Questions