John Davidson

php - Remove All the occurrence of Word from Sentence Using Regular Expression

0 comments
Message:


Hello I want to remove words from sentence below. how can i do this with regular expressions


ABC (+£768.00):Yes, 1 Top Access with 2 Socket (+£28.00):Yes , 2 USB and 2 RJ45 (Black)

I want to remove all the occurrence of words which start with "(+" and ends with "):".


For ex: i want to remove "(+£768.00):" and "(+£28.00):" from above line.


Please help me with this.


Thank You



My Answer:
To remove all occurrences of words that start with a specific pattern using regular expressions in PHP, you can use the `preg_replace` function. Here's an example code snippet that removes all words starting with "ABC":

php
$sentence = "Hello I want to remove words from sentence below. how can i do this with regular expressions_ABC ( £768.00):Yes, 1 Top Access with 2 Socket ( £28.00):Yes , 2 USB and 2 RJ45 (Black)";

$pattern = '/\b\w*ABC\w*\b/';
$replacement = '';

$newSentence = preg_replace($pattern, $replacement, $sentence);

echo $newSentence;


In this code snippet, the regular expression pattern `/\b\w*ABC\w*\b/` is used to match any word that starts with "ABC". The `preg_replace` function is then used to replace all occurrences of such words with an empty string, effectively removing them from the sentence.

Rate this post

3 of 5 based on 2756 votes

Comments




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