John Davidson

php - Laravel find and replace content on the basis of a expression in content coming from Db


I have a blog content in which admin can add pattern like this => %make123%.
when that content is to be displayed i have to replace that %make123% with the vehicle id of 123 but now how to get that 123 from my content. and then make another query to search the vehicle with that id.

this is my controller function for blog detail.

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_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(.+?)%/';



Backend is in laravel and frontend is in react js.

My Answer:
If you want to find and replace content in Laravel based on a specific expression, you can use the `preg_replace` function in PHP. Here's an example of how you can achieve this:

// Assuming $content is the blog content coming from the database
$pattern = '/pattern/';
$replacement = 'replacement';

$newContent = preg_replace($pattern, $replacement, $content);

// Update the blog content in the database with the new content

In this example, the `$pattern` variable contains the regular expression pattern that you want to find in the content, and the `$replacement` variable contains the text that you want to replace it with. The `preg_replace` function will search for the pattern in the content and replace it with the specified replacement text.

Make sure to adjust the pattern and replacement variables according to your specific requirements.

Rate this post

3 of 5 based on 4511 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us