John Davidson

php - Regex to only match two asterisks

0 comments
Message:


I'm sorry if the question is unclear
I am trying to make a regular expression that replaces everything with ** at the beginning and end with "Test" (for now at least.)


Currently this is my pattern:
\*{2}[\w\s]+\*{2}
This works so that strings like **Car**, **123**, **This is a test** get replaced with "Test", except also for example ***Bird*** becomes *Test*.


So my question is if there is a way to make sure strings only get replaced with "Test" when there's exactly two ** at beginning and end, no more (so ***Bird*** stays ***Bird*** and doesn't get replaced).



My Answer:
You can modify your regex pattern to only match exactly two asterisks at the beginning and end of the string by using the following pattern:

php
^\*{2}(.*?)\*{2}$


This pattern will match strings that start with exactly two asterisks, followed by any characters (non-greedy), and end with exactly two asterisks. You can then replace the matched string with "Test" as needed.

Rate this post

4 of 5 based on 9073 votes

Comments




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