【问题标题】:Using str_replace within an already-existing function?在已经存在的函数中使用 str_replace?
【发布时间】:2014-03-24 19:57:44
【问题描述】:

所以现在,我有一个简单的函数用来调用一些文本内容:

function htmlstuff() { ?>
<p>html text content here</p>
<? }

在一个页面上,我使用以下方法调用文本:

<?php htmlstuff() ?>

现在,我需要弄清楚如何对函数中的任何文本使用“搜索和替换”。我尝试过类似

function str_replace($search,$replace,htmlstuff())

但我显然不知道我在做什么。有没有简单的方法来搜索函数中的文本并搜索/替换?

【问题讨论】:

  • 请详细说明您的问题

标签: php function search replace str-replace


【解决方案1】:

你真正想做什么? 如果您想在 htmlstuff 函数的返回变量中搜索和替换,那么 你离正确答案不远了。

function htmlstuff() { 
 $htmlstuff = "<p>html text content here</p>";
 return $htmlstuff;
}

echo htmlstuff();

str_replace($search,$replace,htmlstuff());

这应该可以解决问题

如果您只是想让函数 htmlstuff 更具动态性,那么您应该采用不同的方法。像这样:

function htmlstuff($html) { 
 $htmlstuff = "<p>".$html."</p>";
 return $htmlstuff;
}

echo htmlstuff("html text content here");

【讨论】:

  • 非常感谢!!我想如果有可能我想将 html 保留在“echo”语句之外,这样我就可以使用 Dreamweaver 的快捷方式等编辑原始文本,但似乎完成搜索/替换的唯一方法是让某种引号内的文本。感谢您的意见,我会投赞成票,但我的代表太低了。
  • 完成!哈哈,我是新手,抱歉。你能确认我说的是否准确吗?为了应用搜索/替换,文本是否必须在回声或引号中?不确定我是否清楚,只是当 text/html 在引号内时,Dreamweaver 的快捷方式不起作用。
【解决方案2】:

看起来像这样:

function htmlstuff ($content = "Default text goes here")
{
  echo "<p>" . $content . "</p>";
}

然后在另一个电话中,您只需 htmlstuff("New text to go there");

如果我错了,请纠正我来解决问题

【讨论】:

    【解决方案3】:
    <?php
    
    $html_stuff = htmlstuff();
    $search_for = "Hello, world!";
    $replace_with = "Goodbye, world!";
    
    $html_stuff = str_replace($search_for, $replace_with, $html_stuff);
    
    echo $html_stuff;
    
    function htmlstuff() { 
    echo '<p>html text content here</p> ';
    }
    

    【讨论】:

    • 函数没有返回值,$html_stuff = htmlstuff();将是空的
    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多