hello
I’m building a Filter and need the Categories to be exactly like this:
data-filter="category1 category2 category3"
The categories are stored in a Multiselect field and I try to get them like this:
<?php foreach ($project->categories()->split() as $category): ?><?= $category ?><?php endforeach ?>
which gives me this:
data-filter="category1, category2, category3"
Now I want to remove the commas but keep the spaces. I tried
split(',')
but this removes the spaces too. I also tried to just add Space at the end of <?= $category ?> but this breaks the filter.
Remove the foreach loop, and do this instead:
echo implode( ' ', $project->categories()->split(',') );
split(',')
creates an array from the comma separated list, implode()
joins the array elements into a string using the given separator.
1 Like
Can the spaces in the array be converted to “-” to ensure that categories with two words can still function correctly?
As an example, I have categories named “User Experience, Data” and I need to transform it into user-experience data
so that the filter can function properly. I usually use <?= Str::slug($category) ?>
to convert a string into a slug format, but I am uncertain about how to integrate it with “implode” for my particular use case.
nevermind, chatgpt just gave me the answer:
<?php
$categories = $faqAccordion->categories()->split(',');
$slugs = array_map('Str::slug', $categories);
$slug_string = implode(' ', $slugs);
?>
Replying, because I was looking for this solution too and found a one-liner that does the trick:
The more performant solution should be using preg_replace()
or mb_ereg_replace()
to replace the ,
(comma space) with
(space).
For categories using only ASCII characters do:
preg_replace("/, /", " ", $project->categories())
For all others this should work (untested):
mb_ereg_replace(", ", " ", $project->categories())
See also: mb_ereg_replace
in The PHP Manual