简体   繁体   中英

Any way to optimize my solution for a faster and more elegant approach?

In mySQL, I have a column near_to where I save entries like Public Transportation,Business center

On the frontend I want to display some icons based on these entries. For example an icon when there is Public Transportation inside the field, or Business Center or Fitness Center and so on.

This is my solution so far. My question is, is there any way to make this faster and more elegant?

if (strpos($req['near_to'],'Pub') !==false) {
    echo '<li>public transportation icon</li>';
}
if (strpos($req['near_to'],'Fitn') !==false) {
    echo '<li>fitness icon</li>';
}
if (strpos($req['near_to'],'Busi') !==false) {
    echo '<li>business icon</li>';
}

I made up a little snippet with preg_replace. This way you can define the mapping in one array and get the final result in one statement by running preg_replace on the array itself.

<?php 

$subject = "Public Transportation";
//$subject = "Business center";

$patterns = array(
    "/Pub.*/" => "<li>public transportation icon</li>",
    "/Fitn.*/" => "<li>fitness icon</li>",
    "/Busi.*/" => "<li>business icon</li>"
    );

$html = preg_replace(array_keys($patterns), array_values($patterns), $subject);

echo($html);

UPDATE if you wanna match subjects for more than one of the patterns, than the pattern key must be different. The keys in the patterns array in the above example match the whole string, therefore only one icon will be returned as you said in your comment.

If we change the patterns as below, you'll see multiple icons in the html results. I assumed that the strings are constant and they are separated by ',', where ',' is optional, hence the '?' in the pattern.

<?php 

$subject = "Public Transportation,Fitness Center,Business Center"; //$subject = "Business center";

$patterns = array(
    "/Public Transportation,?/" => "<li>public transportation icon</li>",
    "/Fitness Center,?/" => "<li>fitness icon</li>",
    "/Business Center,?/" => "<li>business icon</li>"
    );

$html = preg_replace(array_keys($patterns), array_values($patterns), $subject);

echo($html);

The above will return

<li>public transportation icon</li><li>fitness icon</li><li>business icon</li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM