PHP - use preg_replace to change the color of a word after a specific character

I currently have a preg-replace to change the colors of the words displayed in a div.

however, for now, these are just text matches.

if (sqlsrv_has_rows($stmt)) 
        {
            $data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);

            echo "<div class='custom-font title-container'>
                    <div class='expand-button-container fa fa-expand' onclick='expandWindow()'></div>
                    <div id='title-container1'><div class='edit-note fa fa-pencil' onclick='editSQLNote()'>&nbsp;&nbsp;&nbsp;</div>" . "<div data-toggle='modal' data-target='#editSQLNoteNameModal' class='display-inline'>" . $data['SQLNoteName'] . "</div>" . "&nbsp;<div class='save-note fa fa-thumbs-up' onclick='saveSQLNote(); submitSQLNoteText();'></div></div>
                  </div>";

            $note = nl2br($data['SQLNote']);
            $note = preg_replace('%(SELECT|FROM|WHERE|INNER|JOIN|DISTINCT|LEFT|OUTER|APPLY|WITH|NOLOCK|DECLARE|ORDER BY|VARCHAR|bit)%m', '<span style="color: red;">$1</span>', $note);
            $note = preg_replace('%(ISNULL|UPDATE|SET|INSERT INTO)%m', '<span style="color: #9A2EFE;">$1</span>', $note);          
            $note = preg_replace('%(IS NOT NULL|AND|IS NULL)%m', '<span style="color: grey;">$1</span>', $note);
            $note = preg_replace('%(BEGIN TRAN|ROLLBACK TRAN|BEGIN|END|CASE|END|WHEN|THEN|ELSE)%m', '<span style="color: blue;">$1</span>', $note);
            $note = preg_replace('%(GETDATE|MAX|CONVERT|UPDATE|CAST|COUNT)%m', '<span style="color: #FA58F4;">$1</span>', $note);

            echo "<div contenteditable='true' id='ta4'>" . $note . "</div>";
        } 
        else 
        {
            echo "No data found";
        }

      

However, I would like to know if there is a way, so if I put the @ symbol, whatever, the next word will be left before the space after the word, that the color will change.

So, if I put @hello and @goodbye, they change to green (including the @ symbol, but only to the end of the word)

however I cannot hardcode the words to say hello and goodbye because they will always be different (they will be declared as variables by the user, so they will always be different).

So, is there a way to dynamically change the color of the words after the @ symbol?

I'm sorry if this doesn't make sense, I tried to explain the best I could.

+3


source to share


1 answer


I think this will do:

$note = preg_replace('%(@.+?\b)%m', '<span style="color: green;">$1</span>', $note);

      



.+?

is a non-greedy match until the first \b

, which is a word boundary (space, but also characters such as ,

, .

and newline).

+2


source







All Articles