简体   繁体   English

如何在回显字符串和函数调用中插入变量?

[英]How do I insert variable inside an echo string and function call?

I checked out this post but no luck : PHP - concatenate or directly insert variables in string 我签出了这篇文章,但没有运气: PHP-连接或直接在字符串中插入变量

The suspect in question: showUser(3, change, " . $name . ");'> $name breaks the code; 有问题的嫌疑人: showUser(3, change, " . $name . ");'> $ name破坏了代码; the second $name does work. 第二个$ name起作用。 The variable does not get passed to the function. 变量不会传递给函数。 I have been testing for hours to get this to work! 我已经测试了几个小时才能使它正常工作! It seems like it should work. 似乎应该可以。 I tried checking other places in the application to see what the problem could be and this seems to be the culprit. 我尝试检查应用程序中的其他位置,以查看可能是什么问题,这似乎是罪魁祸首。

<?php 
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
        if ($hint === "") {

            $hint = "<p onClick='DoIt(); showUser(3, change, " . $name . ");'>" . $name . "</p>";
        } else {
            $hint .= "\n" . "$name";
        }
    }
} 
?>

JavaScript probably is requiring $name to be quoted. JavaScript可能要求使用$ name进行引号。

$hint = "<p onClick='DoIt(); showUser(3, change, \"" . $name . "\");'>" . $name . "</p>";

Escaping the quotes like this will cause them to appear in the JS function call. 像这样转义引号会使它们出现在JS函数调用中。

Quotes are often a thorny problem when mixing PHP, JavaScript and HTML on one line. 当将PHP,JavaScript和HTML一行混合使用时,引号通常是一个棘手的问题。

You can quote your variable like this 您可以像这样引用变量

if ($q !== "") {
  $q = strtolower($q);
  $len = strlen($q);
  foreach($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
      if ($hint === "") {
       $name = "'" . $name . "'";
       $hint = '<p onClick="DoIt(); showUser(3, change, ' . $name . ');">' . $name . '</p>';
      } else {
       $hint .= "\n" . "$name";
      }
    }
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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