Jump to content

match once


glenelkins

Recommended Posts

hi

 

i maybe have a string like "hellohellobyehello"

 

i want to match for "hello" so use:

 

preg_match ( '%hello%', $string );

 

but how would i return true if the string contains only 1 occurance of "hello". so in this example it would be false because there are 3 "hello" in there

Link to comment
Share on other sites

ok all well and good but the string and pattern will have more than just in my example to macth.

 

it may have a string like: '1234hellobyedonttalktome'

 

pattern may be '%1234hello%';

 

only want to make sure the string has 1 occurance of the "hello" but must start with 1234

Link to comment
Share on other sites

If you need to match multiple things you might have wanted to mention that initially. With regular expressions, theres no point in saying I want to match this, getting a pattern then saying oh it must also match this... the chances are the pattern will be changed completely. It's important to know from the outset exactly what needs to be matched. Having said that, in your particular example you're probably better off using multiple patterns. Also using the information provided so far your probably (IMHO) better off using str functions rather than regex.

 

if(substr($input, 0, 4) == '1234' && substr_count($input, 'hello') == 1) {

Link to comment
Share on other sites

preg_match_all("~hello~", $String, $Temp);

if(preg_match("^1234", $String) && sizeof($Temp[0]) != 1)

 

Whilst that would also work (assuming you remembered the delimeters on the preg_match call) it would be slower.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.