【发布时间】:2015-12-23 19:54:40
【问题描述】:
Hy 社区
我在使用 php 时遇到了一些问题,找不到解决方案。我目前正在开发一个wordpress插件,我想做的是操作一些内容。使用 php 缓冲 (ob_start) 效果很好,但给我带来了一些新的麻烦。我正在做的是以下(最小化)。
假设我的网页包含以下文本:
Hy there, my name is A B, I am living in C with my dog D
php 代码在做什么:用子函数的输出替换一组字符串。当然,这只是一个小例子。
<?php
// -----------------------------------------
// The Function loading some content from a php file
function my_function() {
ob_start();
require_once("some_file.php");
$content = ob_get_contents();
ob_end_clean();
return($content); // Returns new content
}
// -----------------------------------------
// Content of the web page
$content = "Hy there, my name is A B, I am living in C with my dog D";
// Strings to replace (by the content returned by "my_function")
$matches = array("A","B","C","D");
// Looping over the different matches
foreach ( $matches as $match ) {
// Calling my_function in buffer mode
$content = str_replace($match,call_user_func("my_function"),$content);
} ?>
好吧,现在发生的情况是缓冲是按定义异步的。一旦第一个 my_function 调用完成,整个缓冲区将被清理,并且“A”不会被“A”替换,但也包含“B”应该替换的部分替换为:)。如果只有一件事要替换,那效果很好(只有一个ob_start 进程)。
是否有任何其他方法可以捕获 include 或 require 调用的输出,或者以同步方式运行 ob_*?也许会有更好的方法我还没有找到。得到提示会很棒:)。
提前致谢!也许我完全走错了路,但这就是学习的方式:)。
复活节快乐, 重做
【问题讨论】:
标签: php synchronization ob-start