【问题标题】:Laravel find and replace content on the basis of a expression in content coming from DbLaravel 根据来自 Db 的内容中的表达式查找和替换内容
【发布时间】:2021-02-16 05:34:34
【问题描述】:

我有一个博客内容,管理员可以在其中添加这样的模式 => %make123%。 当要显示该内容时,我必须将 %make123% 替换为 123 的车辆 ID,但现在如何从我的内容中获取该 123。然后进行另一个查询以搜索具有该 ID 的车辆。

这是我用于博客详细信息的控制器功能。

function blogDetail($blog_id, $title_link){

$dataSetArray = array();
$dataSetArray['route'] = '/blog/:blog_title';

$rs = "SELECT id, post_title, post_meta_title, post_author, post_meta_description, 
post_meta_keywords, 
post_content, post_image, DATE_FORMAT(created_at, '%d-%b-%Y') as created_at FROM blog_post
where id = '$blog_id' AND CONCAT( CONCAT( CONCAT( SUBSTRING(MY_TITLE(post_title), 1, 50),'-'), 
id),'.html') = '$title_link' ";
$results = DB::select($rs);





$results = json_decode(json_encode($results), true);
foreach ($results as $key => $value){
  $content =  $value['post_content'];
}

$pattern = '/%make(.+?)%/';

preg_match_all($pattern,$content,
$out, PREG_PATTERN_ORDER);


}

后端在laravel,前端在react js。

【问题讨论】:

  • 你想从 %make123% 得到 123 吗?
  • 是的@VPC 想要获得 123 但 123 是动态值。然后根据这个id查询
  • 您的$out 现在应该包含一个匹配数组,包括子匹配,它允许您找到数字 123。然后在您的数据库中搜索 123。然后执行 preg_replace 将 make123 替换为您的内容数据库。使用laravel?为什么不使用 eloquent 模型及其查询。你的 foreach 循环也有点奇怪,因为它只为最后一条记录设置内容。

标签: php reactjs regex laravel model-view-controller


【解决方案1】:

使用正则表达式从给定的字符串中获取您的内容 id。

$regex = '/(%)([a-zA-Z]*)([0-9]*)(%)/m';
    
preg_match_all($regex, $content, $matches, PREG_SET_ORDER, 0);
    
// Print the entire match result
echo "<pre>";
print_r($matches[0][3]);
echo "</pre>";

【讨论】:

  • 感谢您的解决方案对我有用,我现在能够根据此 ID 查询数据,您能告诉我,现在我想用新内容替换整个 %make123%。 ?
  • @faizan preg_replace($regex, $change_value, $content);
猜你喜欢
  • 2020-03-13
  • 1970-01-01
  • 2010-10-01
  • 2012-12-30
  • 2014-10-28
  • 1970-01-01
  • 2021-07-01
  • 2013-03-05
  • 1970-01-01
相关资源
最近更新 更多