Splitting a string into arrays in Smarty

This isn’t supposed to be a blog about programming, but I’m working a lot with PHP and Smarty these days, and whenever I manage to crack a problem, I get this strange feeling of acchievement. Then I come here to brag.

Anyway, here goes:

«How do I split a string in Smarty template engine?»

Well kind Sir, that’s quite an easy task. Here’s an example:

{assign var=”teststring” value=”31|32″}
{assign var=”testsplit” value=”|”|explode:$teststring}
{$testsplit[0]}<br />
{$testsplit[1]}

Let’s for example say you have a bunch of Meta Keywords that are bundled together in the database (games,game,online,playing) – and you want to separate them, so that you can create keyword-specific landingpages for on-site search optimalization (games – game - online - playing).

Here’s how you do it:
(we’re assuming you have a variable called $MetaKeywords!)

{* Splitting a long string into a bunch of different arrays *}
{assign var=”keywords” value=”,”|explode:$MetaKeywords}
{foreach from=$keywords item=keyword}
<a href=”/index.php?search={$keyword}”>{$keyword|trim}</a>,&nbsp;
{/foreach}

See what we did above? First we begin by telling the system that we want to create a new variable called $keywords. Then we continue by telling that the value we want to split is “,” and finally we tell it what string to use (in this case, $MetaKeywords).
This results in the string stored in $MetaKeywords being split into different arrays named $keyword[1], $keyword[2], $keyword[3] and so on.
About these ads

3 Comments on “Splitting a string into arrays in Smarty”

  1. Hello! I just want to give an enormous thumbs up for the good info you could
    have right here on this post. I can be coming back to your weblog
    for extra soon.

  2. You will find some service providers on the market which may
    well fix broken hyperlinks like Digi Link Doctor.
    Broken link happens when you type in the wrong URL while coding the page.

    Still they will not give you anything without paying.

  3. Quality content is the secret to invite the visitors to visit the website,
    that’s what this website is providing.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.