4

I have two patterns and i want to search them in a string. they are like this:

$pattern = '/,3$/'
$pattern = '/^1,/';

actually I want to find strings that start with 1, OR end with ,3

My strings are in this format:

a => 1,2
b => 31,2
c => 4,3

for example a and c are matches!
how can I use preg_match to check this patterns?
tanks for helps.

Masoud Nazari
  • 476
  • 2
  • 6
  • 17
  • Loop over them and match it. – Sougata Bose May 12 '15 at 08:18
  • 1
    I'm looking for a way with only one check...! – Masoud Nazari May 12 '15 at 08:18
  • What do you need to match though? do you need to check either if the string starts with 1, OR ends with ,3 or do you need to extract everything which is not that? if you simply need to match, just use the or operator `|`. Else, if you need to match the rest, something like this will work: `(?=^1,(.*?)$)|(?=(.*?),3$)` – briosheje May 12 '15 at 08:24
  • I want to check, but I don't know how to use OR operator. – Masoud Nazari May 12 '15 at 08:26
  • @MasoudNazari: then it's just this: `(^1,)|(,3$)` Test here: https://regex101.com/r/sP8bT8/1 .. ^1, asserts that the string starts with 1, literally. If it doesn't, it checks whether it ends with ,3. – briosheje May 12 '15 at 08:28

3 Answers3

7

Try it this way

preg_match("/^1,|,3$/", $string)
DigitalDouble
  • 1,747
  • 14
  • 26
  • 1
    You need to use preg_match_all since match will find only 1. – Avinash Raj May 12 '15 at 08:53
  • 2
    @AvinashRaj No, that is of no importance here. It is about matching multiple patterns, not how many results to obtain. In this case the first result matching either of both patterns will be returned. That is what OP wanted. – Marki Mar 08 '20 at 15:41
3

/(^1,)|(,3$)/ should work for you.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
frenzy
  • 1,632
  • 3
  • 16
  • 18
2

Just in case some day you will need a non-regex solution, you can use the following startswith and endswith functions:

function startsWith($haystack, $needle) {
        // search backwards starting from haystack length characters from the end
        return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
    }
function endsWith($haystack, $needle) {
        // search forward starting from end minus needle length characters
        return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
    }

if (startsWith("1,2", "1,") || endsWith("1,2", ",3"))
 echo "True1". "\n";
if (startsWith("31,2", "1,") || endsWith("31,2",",3"))
 echo "True2". "\n";
if (startsWith("4,3", "1,") || endsWith("4,3",",3"))
 echo "True3" . "\n";

Output of the IDEONE demo:

True1
True3
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563