dongyiyu882684 2014-05-19 18:43
浏览 28

PHP在文件中找到半个未知的字符串

I am writing some code, but I got stuck at the point where I wanted to implement a language system apart from the database (maybe integrating it later). At the moment I have these lines of code in my language class:

final public function findTexts()
{
    global $engine;
    $file = file_get_contents('./styles/'.$engine->getStyle().''.$engine->getPage());
    if(strpos($file, '%%'))
    {
        echo "String found";
    }
}

Let me show you my other function:

final public function getText($text)
{
    global $engine, $LANG;
    $text = str_ireplace($text, $LANG[substr($text, 2, -2)], $text);
    echo $text;
}

What I wanted to do, is check a file (which is inside a styles folder) for a string (for example %%Hi%%). Inside my language file I says Hi == Hello, so when I do the getText function it will say 'Hello'. But, I want to make it simple so you only have to type %%Hi%% inside your file, and the language class will automatically check all strings containing %% at the beginning, and %% at the end, and will replace the string inside the %% and %% with the given string inside the language file.

Hope that is enough info...

Many thanks!

  • 写回答

1条回答 默认 最新

  • douruanfan3030 2014-05-19 18:52
    关注

    You can accomplish this by using regular expressions and preg_replace_callback. See my example below:

    <?php
    final public function findTexts()
    {
        global $engine;
        $file = file_get_contents('./styles/'.$engine->getStyle().''.$engine->getPage());
        $language = $this;
        $file = preg_replace_callback('/(%%([^%]+)%%)/',function($matches) use ($language){
            $word = $matches[2];
            return $language->getText($word);
        },$file);
    }
    

    This method can become very slow if you have a lot of files or a lot of replacements. It's great if you are doing a very small personal website. If you're doing something a bit bigger, I highly recommend caching the result so you don't have to recompute it for every request and file.

    评论

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目