用PHP搜索文件中的字符串
我创建了一个函数,用于在Laravel中搜索我的视图文件中的所有翻译,如下所示:用PHP搜索文件中的字符串,php,laravel,Php,Laravel,我创建了一个函数,用于在Laravel中搜索我的视图文件中的所有翻译,如下所示: <?php Route::get('/recursive', function (){ $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(base_path('resources/views/'))); foreach($files as $file){ $searchfor = '
<?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]);
}
}
});
我需要从上面的结果中得到的只是这一部分:
'articles.body'
'articles.published_at'
'articles.tags'
我需要在代码中更改什么才能只获得上面的这一部分?本地化助手()之类的工具可以为您轻松做到这一点-只需使用composer安装此库。使用此模式:
/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]
}
我想做我自己的,但当你提出这个问题时,我想知道你是否使用过你发布的内容?它是否扫描所有trans(),然后创建一个刀片视图,我可以通过浏览器编写自己的翻译并保存它们?是的,它扫描所有“trans('*')”使用并生成一个langauge文件-这应该是返回数组的.php文件,就像配置文件一样。酷…这是一个很好的包,但我仍然想自己制作…所以这实际上不是我问题的答案。这个问题更适合那些使用香草PHP的人
<?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]
}