Ndugu
January 29, 2021, 4:22am
21
texnixe:
str_replace()
How do I use str_replace
?
In the docs I can only finde Str::replace()
and I don’t understand anything.
In the image snippet, I tried:
<img class="<?= $block->stil()->str_replace(",", " ") ?>" src="<?= $image->url() ?>" alt="<?= $block->alt()->or($image->alt()) ?>">
but it doesn’t do anything (Not even an error).
texnixe
January 29, 2021, 7:48am
22
str_replace()
is a standard PHP function, not a Kirby function, that’s why it is not in the docs. You can use Str::replace()
instead.
However, since neither of them are field methods (i.e. methods that belong to a field object ), you cannot string them onto the field with ->
but have to use them like this:
echo str_replace(',', ' ', $block->stil()->value());
echo Str::replace($block->stil()->value(), ',', ' ');
If I were you, I’d go for the variant with splitting and imploding I showed above.
Ndugu
January 31, 2021, 3:33pm
23
Both solution do work here!
replace:
echo Str::replace($block->stil()->value(), ',', ' ');?>" src="<?= $image->url() ?>" alt="<?= $block->alt()->or($image->alt()) ?>">
<?php endif ?>
Implode:
<img class="<?php $classArray = $block->stil()->split(','); $classes = implode(' ', $classArray); echo $classes;?>" src="<?= $image->url() ?>" alt="<?= $block->alt()->or($image->alt()) ?>">
Why do you recommend the implode variant?
Did I say “thank you” for saving me a… again?
texnixe
January 31, 2021, 4:40pm
24
Because I think it’s more versatile, you can easily get rid of extra whitespace, get single elements using list()
etc.
Example:
$string = 'a, b, c';
$array = array_map('trim', explode(',', $string));
dump($array);
echo implode(' ', $array);
list($a, $b, $c) = $array;
echo $a . ' ' . $b;
echo $array[0] ?? '';
I’d define my variables outside the image tag for more readable code:
<?php
$classArray = array_map('trim', $block->stil()->split(','));
$classes = implode(' ', $classArray);
?>
<img class="<?= echo $classes ?>"
src="<?= $image->url() ?>"
alt="<?= $block->alt()->or($image->alt()) ?>"
>