Reputation: 10228
I have some string with this style:
$var = "a - it is a string"; // I want this output: 'it is a string'
$var = "m - it is second string"; // I want this output: 'it is second string'
So here is my pattern:
[single character in the first of string]<space>-<space>{anything} // I want just {anything}
How can I do that in PHP REGEX?
Here is my try (altought does not work and I'm sure it is really far of what I want)
preg_replace("/^\w\s+-\s+/","",$str);
Edit:
It should be noted that I use Persian characters in reality. Also here is a example:
$var = 'ی - این یک متن تست است';
Upvotes: 1
Views: 153
Reputation: 107297
First of all you need to change the /w
to \w
.Secondly for matching a single character you can use a character class (if you just want to match alphabetical character) and for match the rest of string you can use modifier .
followed by *
:
preg_replace("/^[a-z]\s+-\s+.*/","",$str);
Also note that since you used the anchor ^
to specify the start of the string, if you are dealing with a multi line string you need to use flag m
and g
for match global.
preg_replace("/^[a-z]\s+-\s+.*/m","",$str);
See demo https://regex101.com/r/gT9wB8/1
Reed more about regex https://www.regular-expressions.info
If you are dealing with unicode strings you can use flag u
which makes your regex engine to match the unicode characters.
also note that you need to change range of your characters or use dot .
which match just one character (but all the characters):
'/^.\s+-\s+.*/mu'
Or:
'/^[\u0622-\u06cc]\s+-\s+.*/mu'
Demo https://regex101.com/r/gT9wB8/2
Upvotes: 1
Reputation: 785276
You can use this:
$var = 'ی - این یک متن تست است';
echo preg_replace('/^\p{L}\h+-\h+/u', '', $var);
//=> این یک متن تست است
Regex used is:
^\p{L} # match unicode letter at start
\h+ # match 1 or more horizontal space
- # match 1 hyphen
\h+ # match 1 or more horizontal space
Important is use of /u
modifier for unicode support in this regex.
Upvotes: 1
Reputation: 98921
preg_replace('/^.\s-\s/', '', $var);
Live PHP Demo
Regex Explanation
^.\s-\s
Assert position at the beginning of a line «^»
Match any single character that is NOT a line break character «.»
Match a single character that is a “whitespace character” «\s»
Match the character “-” literally «-»
Match a single character that is a “whitespace character” «\s»
Upvotes: 2