I need to septate out some paragraph from my file, it's start with some string and end with special character like ! I am using preg_match_all to get the result, please find below link and select preg_match_all http://www.phpliveregex.com/p/m5C
and I want output like
0=> array(
0=> ip vrf Access-Mgmt
rd 65000:3298
route-target export 65000:4585
route-target export 65000:4717
route-target import 65000:4585
route-target import 65000:2659
)
I don't see the need for regex in this specific case because you want the first portion the precedes the first !
. strstr()
does this well. explode('!',$string,2)[0]
will work but it is a less direct hack, because it generates an array before extracting the desired string from the first element.
Code:
echo trim(strstr($string,'!',true));
Output:
ip vrf Access-Mgmt
rd 65000:3298
route-target export 65000:4585
route-target export 65000:4717
route-target import 65000:4585
route-target import 65000:2659
Or if you are not targeting the first block of text, and rather want the Access-Mgmt
block, you can use preg_match()
with this pattern: /ip vrf Access-Mgmt[^!]+/
Demo or trim the trailing newline character with /ip vrf Access-Mgmt[^!]+(?=\R)/
.
Here is what these calls can look like:
var_export(preg_match('/ip vrf Access-Mgmt[^!]+/',$string,$out)?$out[0]:'fail');
// or
var_export(preg_match('/ip vrf Access-Mgmt[^!]+(?=\R)/',$string,$out)?$out[0]:'fail');
// or
var_export(preg_match('/ip vrf Access-Mgmt[^!]+/',$string,$out)?trim($out[0]):'fail');
You can checkout the preg_match_all at http://www.phpliveregex.com/p/m5H
What I've done is splitted the string with the condition ([^!]*)! and replacement $0
Explanation:
( - start capture group
[ - start capture group
^! - match anything but ! symbol
] - start capture group
* - match 0 or more occurances
) - start capture group
! - followed by ! symbol
$0 - First capture group
Let me know if this solves your use case.
Output:
1 => Array(
0 => Array(
ip vrf Access-Mgmt
rd 65000:3298
route-target export 65000:4585
route-target export 65000:4717
route-target import 65000:4585
route-target import 65000:2659
),
1 => Array(
ip vrf Atheeb-VoIP
rd 65000:4592
import map Atheeb-VoIP_Imp
route-target export 65000:6277
route-target import 65000:6275
route-target import 65000:6276
route-target import 65000:6277
),
2 => Array(
ip vrf CISCO
rd 65000:1
route-target export 65000:1
route-target import 65000:1
),
3 => Array(
ip vrf EBU-Modem-DHCP
rd 10:10
route-target export 65000:6475
route-target import 65000:6476
),
4 => Array(
ip vrf ER-DCN
rd 65000:3719
route-target export 65000:5241
route-target import 65000:5241
route-target import 65000:5242
),
5 => Array(
ip vrf ER-LTE-Media-Signalling
rd 65000:3723
route-target export 65000:5245
route-target import 65000:5245
route-target import 65000:3507
route-target import 65000:3511
route-target import 65000:5535
),
6 => Array(
ip vrf ER-LTE-OAM
rd 65000:3724
route-target export 65000:5247
route-target import 65000:5247
),
)