user3510921
user3510921

Reputation: 1

Replacement does not working in case of using BBcode in php

Suppose, I have a string '@[52:] loves his mother very much'. I want the string to be replaced with 'Allen loves his mother very much'. Explanation: when any match found in my string with syntax '@[numeric_id:]' then these matches will be replaced with the name of the user exist with the 'numeric_id' in 'user_entry' table. If match found in the string but no user found with the numeric_id in 'user_entry' table then it will return the exact string like '@[52:] loves his mother very much'.

I tried to do it with 'preg_replace' function in php. 'preg_replace' successfully collects all matches with syntax '@[numeric_id:]' but it can't send matches to a user defined function named 'test()'. In short my code does not working.

I have the following code in test.php file: .

<?php
function test($v) { $con=mysqli_connect("mysql14.000webhost.com","a8622422_jhon","pjdtmw7","a8622422_person");
$safe_id=preg_replace("/[^0-9]/",'',$v);
$sql="SELECT * FROM user_entry WHERE u_id='$safe_id'"; 
$result=mysqli_query($con,$sql);
$count=mysqli_num_rows($result); $found=''; 
 if ($count==1) {
$row=mysqli_fetch_array($result);
$found=$row['name']; 
} else { $found=$v; } return $found;
 } ?>
<?php 
$post='@[61150631867349144:] & @[59670019475743176:] are friends'; 
echo preg_replace('/(@\[[0-9]+\:+\]+)/',test('$1'),$post);  
?>

I think, the code should return: 'Baki Billah, Mahfuzur rahman and mahi are friends'. But it returns: '@[61150631867349144:] & @[59670019475743176:] are friends'.

How can I do that? What's wrong with my code? Is there any way to do it? If it is impossible to do the action with above code, then please give me the correct & full code of test.php file so that I can do the action explained in the first part of my question.

Any help will be strongly appreciated (I'm working with php). Thanks in advance.

Upvotes: 0

Views: 73

Answers (1)

Steve H
Steve H

Reputation: 966

If you want to execute code for each match of a regular expression the best way is to use the preg_replace_callback function. It can take the same pattern as you are using now but will call a given function for each match.

For example:

echo preg_replace_callback('/(@\[[0-9]+\:+\]+)/', 'test', $post);

You will need to modify your test function the receive an array of sub-matches. $v[0] will be the entire string match.

Upvotes: 1

Related Questions