I'm currently using Opencart (1.5.6.1) to run a multistore, I have a store that has lots of products but they all have to have the same name, Now in the back-end I have "Blah - Tshirt 15" "Blah - Tshirt 16" and so on...
Within opencart there is a foreach loop
<?php foreach ($products as $product) { ?>
<?php if ($product['name']) { ?>
<?php if ($product['product_href']) { ?>
<div class="name">
<a href="<?php echo $product['product_href']; ?>">
<?php echo $product['name']; ?>
</a>
</div>
<?php } else { ?>
<div class="name">
<?php echo $product['name']; ?>
</div>
<?php } ?>
<?php } ?>
Now the output of this on a page, does what it says, outputs the Product name "Blah - Tshirt 15" or whatever they're called.
But what if on the page that a customer see's my client want EVERY tshirt to just say
"Blah - Tshirt"
Is there an easy way to either str replace
, or trim
the code to say, remove the last 1 or 2 Characters from the $product[name]
I'm not a huge PHP expert, i know a little, but i can't figure it out...
There is a PHP function called substr
http://nl3.php.net/substr . You could use substr($product['name'], 0, -1);
This will remove the last character. If you use -2
it will remove the last 2 characters and so on.
substr('yourstring'{string}, startindex{int}, endindex{int});
I'd use substr($product['name'], 0, -2)
to cut the last 2 characters off a string using substr.
However, if you want to remove all numbers from a string, use regex. Like preg_replace("/[0-9]/", "", $product['name']);
from this SO post. It uses preg_replace.
You can delete the last n characters with substr($var, 0, -n)
as the others suggested. But if you want to delete "a space followed by any amount of digits at the end of the string", use regular expressions instead: preg_replace('/ \d+$/', '', $var)
.
In Your template just replace this line
<?php echo $product['name']; ?>
with this line
<?php echo substr($product['name'], 0, strpos($product['name'], '- Tshirt') + 8); ?>
This should lead to this result:
Blah - Tshirt 1 -> Blah - Tshirt
Blah - Tshirt 15 -> Blah - Tshirt
Blah - Tshirt 150 -> Blah - Tshirt
without the trailing space.