使用PHP搜索文件中的字符串

时间:2017-10-14 21:07:05

标签: php laravel

我创建了一个函数来搜索Laravel中我的视图文件中的所有翻译,它看起来像这样:

<?php

Route::get('/recursive', function (){
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(base_path('resources/views/')));

    foreach($files as $file){

        $searchfor = 'trans';

        // the following line prevents the browser from parsing this as HTML.
        header('Content-Type: text/plain');

        // get the file contents, assuming the file to be readable (and exist)
        $contents = file_get_contents($file);
        // escape special characters in the query
        $pattern = preg_quote($searchfor, '/');
        // finalise the regular expression, matching the whole line
        $pattern = "/^.*$pattern.*\$/m";
        // search, and store all matching occurences in $matches
        if(preg_match_all($pattern, $contents, $matches)){
            echo implode("\n", $matches[0]);
        }
    }
});

并且此函数获取所有可以的翻译。但它完全符合翻译的要求:

{!! Form::label('body', trans('articles.body')) !!}
{!! Form::label('published_at', trans('articles.published_at')) !!}
{!! Form::label('tags', trans('articles.tags')) !!}

我从上述结果中得到的只是这一部分:

'articles.body'
'articles.published_at'
'articles.tags'

我需要更改代码才能获得上述部分?

2 个答案:

答案 0 :(得分:1)

使用此模式:

/trans\((.+?)\)/m

<强>详情

trans    # the word "trans", literally
\(       # open parentheses, literally
(.+?)    # anything, ungreedily, in a capturing group
\)       # close parentheses

获取$matches中的第二个元素,而不是第一个元素,以便获取捕获组中的内容(您正在寻找的内容)而非整个匹配:

<?php
$contents = "{!! Form::label('body', trans('articles.body')) !!}
garbage line
{!! Form::label('published_at', trans('articles.published_at')) !!}
gibberish
{!! Form::label('tags', trans('articles.tags')) !!}
blah blah
hello";
// finalise the regular expression, matching the whole line
$pattern = "/trans\((.+?)\)/m";
// search, and store all matching occurences in $matches
if (preg_match_all($pattern, $contents, $matches)) {
    echo implode("\n", $matches[1]); // $matches[1], not $matches[0]
}

<强>结果

  

&#39; articles.body&#39;
  &#39; articles.published_at&#39;
  &#39; articles.tags&#39;

Demo

答案 1 :(得分:0)

本地化助手(https://github.com/potsky/laravel-localization-helpers)等工具可以轻松完成这一任务 - 只需使用composer安装此库。