简体   繁体   中英

Put a lang function inside of a php string

Trying to do a translation of my MySQL DB to PHP.

Here's the code:

$sql = "SELECT Name, Price FROM utf WHERE Name LIKE 'K%'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th></tr></div>";
    // output data of each row
   while($row = $result->fetch_assoc()) {
    $name = str_replace('K', 'Karambit', $row['Name']);
    echo "<tr><td>".$name."</td><td>".$row["Price"]." ".$row["Trend"]."</td></tr>";
}
   echo "</table>";

So Select, Filter by signature character, and then translate.

Now, I have a lang.php file which has the translations.

Here it is:

<?php
function lang($phrase){
    static $lang = array(
        'ba' => 'Bayonet',
        'ka' => 'Karambit'
    );
    return $lang[$phrase];
}
?>

How do I put it in this line:

$name = str_replace('K', 'Karambit', $row['Name']);

and replace 'ka' => 'Karambit' with 'Karambit' ?

Non of these have worked:

//attempt 1
$name = str_replace('K', 'lang('ka');', $row['Name']);
//attempt 2
$name = str_replace('K', '$lang('ka');', $row['Name']);
//attempt 3
$word = echo lang('ka');
$name = str_replace('K', '$word', $row['Name']);

Don't put function calls in quotes, just use:

$name = str_replace('K', lang('ka'), $row['Name']);
                       //^^^^^^^^^^ See here

Also to give you another option:

You can store your search => replace values into an array like this:

$searchReplace = [
    "ba" => "Bayonet",
    "ka" => "Karambit",
];

And then you can simply use strtr() to replace it, eg

$name = strtr($row['Name'], $searchReplace);

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