我是新手。如果这个问题太基础,我很抱歉,但我想不出最好的方法。
我有很多php文件,其中包含各种文本占位符。例如,在我的.php文件中,我会有这样的东西:
我很喜欢xCity,想住在那里。
或者链路,
<a href="xcity_is_awesome.php">
我想我可以在每个页面的头部使用一些php代码来执行preg_replace,将"xcity"或"xcity"的任何实例分别替换为"mycity"或"mycity"。
我目前可以让这个工作:
< ?php
$xCity = "Mycity"; ?>
只要我用替换文档中所有出现的"xCity"
<?php echo $xCity ?>
我知道有更聪明的方法可以做到这一点,但正如我所说,我是一个全新的人。
有人能帮我吗?
以下是我现在正在尝试的:
使用下面的一个例子,我似乎无法让它发挥作用。
我在文档中将几个变量从"xcity"更改为"{{xcity}}"。
这是我在php文件中的代码:
<?php
$xCITY = "MYCITY";
$xcity = "mycity";
$find = array('{{xCITY}}','{{xcity}}');
$replace = array($xCity,$xcity);
$content = str_ireplace($find,$replace,$content);
?>
当我上传文件并预览它时,php不会更改文本。我确信我一定做错了什么
我目前正在使用SpencerJ的建议(如下):
<?php
$xCity = "Calgary"; ?>
然后使用echo语句来交换变量:
<?php echo $xCity ?>
我似乎遇到了php的问题,包括:
<?php include("<?php echo $xcity ?>_bottomlinks.php"); ?>
现在,我打赌有一个问题,多个php"命令"像这样相互关联。该如何处理?
您应该能够在大多数IDE中的项目中进行查找和替换,以使用<?php echo $xCity; ?>
更改xCity。对于<?php $xCity = "Mycity"; ?>
的前缀,您可以在任何也允许regex搜索的IDE中使用/^/s
(或类似的东西)进行同样的操作,尽管手动添加可能更容易,只添加到需要它的文件中。
代替:
<div>My city is xCity and I think xCity is the coolest city in the world. Everyone should live in xCity!</div>
用途:
<?php $xCity = 'Calgary'; ?>
<div>My city is <?php echo $xCity; ?> and I think <?php echo $xCity; ?> is the coolest city in the world. Everyone should live in <?php echo $xCity; ?>!</div>
$str = '<?php echo $xCity ?>';
echo str_replace('xCity', 'Mycity',$str);
输出-
<?php echo $Mycity ?>
检查-http://codepad.org/uVs6w3kH
让我知道这是不是你想要的?
您可以使用输出控制功能:
<?php
$xCity = "Mycity";
ob_start(); // tell php you want it to buffer the output, not send it to the browser yet
?>
Text containing xCity
and maybe other stuff to replace
<?php
// now the page is complete, get the contents (and empty the output buffer)
$out = ob_get_clean();
// replace all the strings you want replaced
...
// and send the output to the browser
echo $out;
?>
其优点是,您实际上不需要触摸页面本身,只需将它们封装在输出缓冲区中即可。但从长远来看,也许使用一个合适的基于php的模板系统会更容易维护。
如果要使用占位符,请使其唯一,从而为其提供边界
例如:<a href="{{xcity}}_is_awesome.php">
通过这种方式,您可以保护变量,如:
CCD_ 5。
<?php
$find = array('{{xcity}}','{{mycity}}');
$replace = array($xcity,$mycity);
$content = str_ireplace($find,$replace,$content);
?>
或者,更好的方法是定义要在脚本中使用的实际PHP变量。
E.G在您的文件中:<a href="<?php echo $xcity ?>_is_awesome.php">
,然后在调用文件/视图时,您可以传递值。
<?php
//define your values
$data['xcity'] = "Some Value";
//load view and pass your variables to it
$content = loadContentView('TheFile', $data);
function loadContentView($view, $data=null){
$path = './path/to/the/files/'.$view.'.php';
if (file_exists($path) === false){
die('Content view not found: '.$path);
}
/*Extract the $data passed to this function*/
if($data !== null){
extract($data);
}
ob_start();
require($path);
$return = ob_get_contents();
ob_end_clean();
return $return;
}
?>
希望它能帮助。。。
$webpage = file_get_contents('mypage.html');
$findme = array('xcity','mycity');
$replace = array('mycity','Mycity');
$webpage = str_replace($findme,$replace,$webpage);
echo $webpage;