Jump to content

[SOLVED] Preg_match_all problem.


JChilds

Recommended Posts

I have a list of Offices, and which level of a building they are on.

 

Eg:

 

Secretary Office (floor 12)

Employee Gym (floor 7)

 

I want to extract particular things. in this example, I want to know which level the Secretary Office is on.

 

I thought I would try:


preg_match_all("/Secretary Office (floor [1-9]?\d+/",$input,$secretary);
$secretary[$x] = ltrim($secretary[$x],'Secretary Office (floor ');

 

But it's having trouble with the ( before 'level'

Giving the error:

Compilation failed: missing ) 

 

Any idea how I can get around this problem?

Link to comment
https://forums.phpfreaks.com/topic/109501-solved-preg_match_all-problem/
Share on other sites

Parens are metacharacters that must be escaped if you want to match a literal.

 

<pre>
<?php
$data = <<<DATA
Secretary Office (floor 12)
Employee Gym (floor 7)
DATA;

preg_match_all('/^([^()]+)\s+\(floor\s+(\d+)\)/m', $data, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$result[$match[1]] = $match[2];
}
print_r($result);
?>
</pre>

Parens are metacharacters that must be escaped if you want to match a literal.

 

<pre>
<?php
$data = <<<DATA
Secretary Office (floor 12)
Employee Gym (floor 7)
DATA;

preg_match_all('/^([^()]+)\s+\(floor\s+(\d+)\)/m', $data, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$result[$match[1]] = $match[2];
}
print_r($result);
?>
</pre>

 

This will give me all the floor numbers, I only want the secretary floor number.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.