[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 436
  • Last Modified:

quick regex exercise with preg_match()

Hello, I have a quick regex exercise I need to get be fore I can move on and for the life of me it has been stumping me for many hours to day... could some one shed a little light on this please thank you..

jeremyBass


from
         $category_name ="HARD DRIVES - WESTERN DIGITAL IDE";
         preg_match('/[^?*](\s\-\s)[^?*]/', $category_name, $matches);
                  echo "Main Cat is: {$matches[0]}\n";
            echo "Sub Cat is: {$matches[2]}\n";


so I'd have

Main Cat is: HARD DRIVES
Sub Cat is: WESTERN DIGITAL IDE


but what I get is
Main Cat is: S - W
Sub Cat is:
0
jeremyBass26
Asked:
jeremyBass26
2 Solutions
 
ozoCommented:
did you mean
'/(.*)\s\-\s(.*)/'
0
 
Terry WoodsIT GuruCommented:

$category_name ="HARD DRIVES - WESTERN DIGITAL IDE";
preg_match('/^([a-zA-Z ]*?)(\s\-\s)(.*)/', $category_name, $matches);
echo "Main Cat is: {$matches[1]}<br>\n";
echo "Sub Cat is: {$matches[3]}<br>\n";

Open in new window

0
 
Terry WoodsIT GuruCommented:
Output from that is:
Main Cat is: HARD DRIVES
Sub Cat is: WESTERN DIGITAL IDE

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jeremyBass26Author Commented:
preg_match('/^([a-zA-Z ]*?)(\s\-\s)(.*)/', $category_name, $matches);

works... but what if it was

kdi4ds s dkf52!  -  kdirsl kd slF9

is it general enough for that?

thank for the help...
0
 
jeremyBass26Author Commented:
it was alittle bit of both...
preg_match('/^(.*)(\s\-\s)(.*)/', $category_name, $matches);

thanks for the help


cheers
jeremy
0
 
ddrudikCommented:
The pattern in the accepted solution would be generic enough to match all such strings containing a '-' character.
<pre>
<?php
$category_name ="kdi4ds s dkf52!  -  kdirsl kd slF9";
echo preg_match('/(.*)\s\-\s(.*)/', $category_name, $matches) ? "Main Cat is: {$matches[1]}\nSub Cat is: {$matches[2]}\n" : "no match found." ;
?>

Open in new window

0
 
jeremyBass26Author Commented:
hey there ddrudik... rock on.. that works great... probably what was meant in the first one now that I look at it...

think you could look at this... and double check the suggestions to see if they are suppost to work?

http://www.experts-exchange.com/Programming/Languages/Regular_Expressions/Q_24121684.html

cheers
jeremy
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now