How do I add a prefix before my table in php? [closed]

0

How do I add a prefixo before my tabela in php? Here is my code below:

$table = 'news AS N, news_category AS NC';

if (strpos($table, ', ') !== false) { 
    foreach (array($table) as $key => $value) {
        $db = $value;
    }
    echo $db;
} else { 
    echo 'FAIL'; 
}

I am returning the following value: news AS N, news_category AS NC

Well now I would like to leave this: prefixo_ news AS N, prefixo_ news_category AS NC , within the code I shared above. Remembering that I do not want to do this: $table = 'prefixo_news AS N, prefixo_news_category AS NC' in variable $table , I need inside if or foreach. Is it possible?

    
asked by anonymous 10.10.2018 / 23:41

2 answers

0

Splits an array into parts and traverses the elements by adding the prefix:

$table = 'news AS N, news_category AS NC';

$prefixed = "";

if (strpos($table, ', ') !== false) {
    //O explode divide a string em um array pelo primeiro parâmetro
    foreach (explode(", ", $table) as $value) {
        //Adiciona a $prefixed o valor com o prefixo
        $prefixed .= ", prefix_$value";
    }
    //Remove o primeiro prefixo
    $prefixed = trim($prefixed, ", prefix_");
    echo $prefixed;
} else { 
    echo 'FAIL'; 
}

Or:

$prefixed = implode(", prefix_", explode(", ", $table));
    
11.10.2018 / 01:33
0

You can use substr([string], [começa_na_posição], [vai_ate]) , for example:

if (substr($table, 0, 2) === ', ') {
    
11.10.2018 / 01:03