Link to home
Create AccountLog in
PHP

PHP

--

Questions

--

Followers

Top Experts

Avatar of Pedro Chagas
Pedro Chagas🇵🇹

Check if string contain multiple dashes (-) characters in php

Hi E's,

I need a solution, to know if there are multiple dashes in a string.

I try to do like this, but no work:

$str = "--test---teste---";
if(preg_match('#(-\s*)+#i', $str)){
    echo "contain";
}
//atention, "-test-test-" is correct!

Open in new window

What I did wrong?


The best regards,

JC

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


ASKER CERTIFIED SOLUTION
Avatar of Scott BennettScott Bennett🇺🇸

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Avatar of gr8gonzogr8gonzo🇺🇸

I know you've already selected the answer but a regular expression is probably overkill here.

If you are just looking to see if there are two dashes in a row, then use strpos():

if(strpos($str,"--") !== false)
{
    echo "there are 2 dashes in a row in the string.";
}

Open in new window


If you just want to check for at least one dash, use the same code but use "-" instead of "--".

If you want to count how many dashes there are in the string, use substr_count():

echo "There are " . substr_count($str,"-") . " dashes in the string.";

Open in new window

The only reason to use a regular expression is if you need to check for spaces between the dashes.


yeah, that is true... since it is 2 or more, just looking for 2 would be sufficient. I just saw the flaw in your regular expression and fixed that, but it really isn't even needed if that is all you are looking for.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.

PHP

PHP

--

Questions

--

Followers

Top Experts

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.