如何从循环短语的开头和结尾删除空格

问题描述:

i need to remove whitespaces from the beginning and end of loop phrase

All words come from an loop, and look like this: " Hello all people "

I'm using the code -

$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
foreach ($appliedFilters as $item) {
        if ($item->getFilter()->getRequestVar() == 'b_car' || 'c_model' || 'd_year') {
            $n_str = string.replace("\"", "", $item->getLabel()));
                   echo $n_str;
                    }
                    }

This code returns "Helloallpeople"

But i need "Hello all people"

Please help!

UPDATED

var_dump($item->getLabel()); returns string(7) "Hello " string(8) "all " string(5) "People "

Try Regx like the following:

$returnValue = preg_replace("/>\s+(.*)\s+</", '>$1<', '<a> Hello all people <a/>');

I am keeping the old answer for reference. But if you simply want to remove leading and trailing spaces; use trim()

Update:

If you want to trim each and every element of an array; you can map trim function to it. Then you can also implode the array to a string.

<?php
$str = array(" Hello all  ", " Hello all people ", "  all people ", " Hello people ");
$n_str = array_map("trim",$str);
var_dump($n_str);
echo implode(" ",$n_str);
?>

Update 2:

Ok I got it; It's not an array. It's a loop. Every time $item->getLabel() returns just a string. it's not an array. Following should help you.

$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
$result = "";
foreach ($appliedFilters as $item) {
        if ($item->getFilter()->getRequestVar() == 'b_car' || 'c_model' || 'd_year') {
            $result .= " ".trim($item->getLabel());
        }
}
echo trim($result);

Try this:

$words = $item->getLabel(); //array(" Hello", "all ", "people "); 
echo trim(preg_replace("/\s+/", " ", implode($words, " ")));

// Output: Hello all people

See demo