-2

I have a string, suppose $string which contains text to be converted through nl2br.
But, these text posts contain links to attachments, like [attachment=300] points to an attachment with id 300 (id is given through database).

What I want is, that if the string contains the phrase [attachment=*](let * be any number),
it first fetches the address of file from database and then replaces [attachment=*] to for example <img src="#">(where # is the address of the file with id *).

Can someone help?

Til
  • 5,150
  • 13
  • 26
  • 34
  • Have you tried anything or just waiting for code? – u_mulder Apr 11 '19 at 19:15
  • @u_mulder I cant understand what I have to do here. I am kinda newbie in PHP – SHIVANK KACKER Apr 11 '19 at 19:18
  • this can help . https://stackoverflow.com/questions/15737408/php-find-all-occurrences-of-a-substring-in-a-string . have a look into array_walk may be not ! – zod Apr 11 '19 at 19:29
  • @zod that only answers half my question, I want to spot all occurrences but also convert them into specific words with using databases. – SHIVANK KACKER Apr 11 '19 at 19:35
  • may be you should try something now and then post again where you are stuck. "convert them into specific words with using databases" otherwise how you explain that – zod Apr 11 '19 at 19:37
  • 1
    This sounds like a job for [`preg_replace_callback()`](https://www.php.net/manual/en/function.preg-replace-callback.php) – Barmar Apr 11 '19 at 19:57
  • @Barmar I cant understand how I must use it. Can you post an answer? – SHIVANK KACKER Apr 11 '19 at 20:12
  • click it man . code is there – zod Apr 11 '19 at 20:18
  • We don't write code for you, we help you fix your code. What part of it don't you understand? – Barmar Apr 11 '19 at 20:18
  • You write a regular expression that matches `[attachment=*]`. The function receives the string that matches the regexp, does the database lookup, and returns the `` string that will be put in its place. – Barmar Apr 11 '19 at 20:20
  • There are lots of examples in the documentation. – Barmar Apr 11 '19 at 20:21

1 Answers1

0

Sorry if I appeared to have been demanding for code, but I just could not find out a way of doing it. So I sat up and FINALLY found out a solution through jquery.

First I str_replaced every [attachment= to <img src=. Then this-

<script>
$(document).ready(function(){
    jQuery.each($('.textpost img'), function(){
        var img = $(this);
        var imgid = $(this).attr('src');

        $.ajax({
            url: 'inc/fn/imgfetch.php?i='+imgid,
            success: function(data) {
                var imgaddr = data;
                img.attr('src','med/img/posts/'+imgaddr);
            }
        });
    });
});
</script>

So glad I finally solved it, and sorry if I failed to understand your advice as I am still learning PHP.