How to search a substring in PHP array using regExp - regex

$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
)
How to get all subarray which contains foo substring with its value using php and regExp.
Expected Output:
$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('foo_test3','demo_test3')
)

You should be able to do it with
preg_grep($pattern,$array)

$input = array( /* your array */ );
$output = array();
foreach ( $input as $data ) {
$len = length($data);
for ( $i = 0; $i < $len; ++$i ) {
if ( strpos($data[$i], 'foo') > -1 ) {
$output[] = $data;
break;
}
}
}

$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
);
$search = 'foo';
$res = array();
foreach ($array as $arr) {
foreach ($arr as $value) {
if (preg_match('~'.preg_quote($search,'~').'~',$value)) {
// if one of the values in that array
// has the search word in it...
$res[] = $arr; break;
// push it into the $res and break
// the inner foreach loop
}
}
}
print_r($res);

Related

Format AWS Transcribe Audio Identification

I've been searching for this solution, couldn't find anything reasonably to what AWS currently have on their UI, so came up with mine in laravel, and dropping it here to help anyone hopefully searching for this as well.
public function convertTextToSpeakers($response)
{
$segments = $response['results']['speaker_labels']['segments'];
$items = $response['results']['items'];
$result = [];
foreach ($items as $key => $item) {
if (!isset($item['start_time'])) {
$prev_item = $items[$key - 1];
if ($prev_item) {
$item['start_time'] = $prev_item['start_time'];
$item['end_time'] = $prev_item['end_time'];
$items[$key] = $item;
}
}
}
foreach ($segments as $key => $segment) {
$has_data = true;
$temp_key = $key;
while ($has_data) {
$temp_key++;
$next_segment = $segments[$temp_key] ?? null;
if ($next_segment && $next_segment['speaker_label'] == $segment['speaker_label']) {
$itemsData = array_merge($segment['items'], $next_segment['items']);
$segment['items'] = $itemsData;
unset($segments[$temp_key]);
$segments[$key] = $segment;
} else {
$has_data = false;
}
}
}
$items = collect($items);
$segments = collect($segments)->sortBy('start_time');
foreach ($segments as $segment) {
$text = '';
$segmentItems = collect($segment['items'])->sortBy('start_time');
foreach ($segmentItems as $seg_item) {
$words = $items->where('start_time', $seg_item['start_time'])
->where('end_time', $seg_item['end_time']);
foreach ($words as $word) {
$text .= $word['alternatives'][0]['content'];
}
$text .= " ";
}
$result[] = [
'speaker' => $segment['speaker_label'],
'text' => $text,
];
}
return $result;
}

Perl Regex Extract first two section of windows path

I want to write a method to extract first two sections of windows path in Perl.
For example,
'D:\git_root_tfs\WorkStation\Projects\InterACT\Tools\server-rule-checker'
Extract as:
'D:\git_root_tfs\WorkStation'
sub Split_Location_as_VMPath {
my $location = shift;
# ^([d-z]:\\.+?\\.+?)\\
# ^(?:\\.*\\.*)\\
if($location ~~ m/^(?:\\.*\\.*)\\/){ # the path drive start from D to E;
# print "VMPath=$1\n";
# push #$vmPathList, $1;
return Convert_to_Lowercase($1);
}
return "Invalid Path $location";
}
How to write the regex?
Test case:
{
my $item = Split_Location_as_VMPath('D:\VM\ia7-BGCDev8.1\test.vhd');
my $expected = Convert_to_Lowercase('D:\VM\ia7-BGCDev8.1');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('E:\Hyper-V-2\ia-int-7.1Beta\test.vhd');
$expected = Convert_to_Lowercase('E:\Hyper-V-2\ia-int-7.1Beta');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\VM\ia7-int-7.1\test.vhd');
$expected = Convert_to_Lowercase('D:\VM\ia7-int-7.1');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\VM\ia7-int-8.1B153\test.vhd');
$expected = Convert_to_Lowercase('D:\VM\ia7-int-8.1B153');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)\test.vhd');
$expected = Convert_to_Lowercase('D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\git_root_tfs\WorkStation\Projects\InterACT\Tools\server-rule-checker');
$expected = Convert_to_Lowercase('D:\git_root_tfs\WorkStation');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
}
Don't use a regex for file processing.
Instead use a module like File::Spec or Path::Tiny.
use strict;
use warnings;
use File::Spec;
while (<DATA>) {
my ($vol, $dir, $file) = File::Spec->splitpath($_);
my #dirs = File::Spec->splitdir($dir);
#dirs = #dirs[0..2] if #dirs > 3;
$dir = File::Spec->catdir(#dirs);
my $path = File::Spec->catpath($vol, $dir);
print "$path\n";
}
__DATA__
D:\VM\ia7-BGCDev8.1\test.vhd
E:\Hyper-V-2\ia-int-7.1Beta\test.vhd
D:\VM\ia7-int-7.1\test.vhd
D:\VM\ia7-int-8.1B153\test.vhd
D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)\test.vhd
D:\git_root_tfs\WorkStation\Projects\InterACT\Tools\server-rule-checker
Outputs:
D:\VM\ia7-BGCDev8.1
E:\Hyper-V-2\ia-int-7.1Beta
D:\VM\ia7-int-7.1
D:\VM\ia7-int-8.1B153
D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)
D:\git_root_tfs\WorkStation
Correct regex is ^([d-z]:\.+?\.+?)\.
sub Split_Location_as_VMPath {
my $location = shift;
# ^([d-z]:\\.+?\\.+?)\\
# ^(?:\\.*\\.*)\\
if($location ~~ m/^([D-Z]:\\.+?\\.+?)\\/){ # the path drive start from D to E;
# print "VMPath=$1\n";
# push #$vmPathList, $1;
return Convert_to_Lowercase($1);
}
return "Invalid Path $location";
}
Using regex in this context is an interesting homework for students. Outside school, you should use the standard modules dedicated for this task:
use File::Spec;
sub Split_Location_as_VMPath {
my $location = shift;
my ($volume, $directories, $file) = File::Spec->splitpath($location);
my #dirs = File::Spec->splitdir($directories);
return "Invalid Path $location" unless #dirs > 2;
return lc File::Spec->catpath($volume, File::Spec->catdir(#dirs[0..2]));
}

Error occurs with while Loop PHP / MySQL NuSOAP

I have created a PHP / MySQL based web service. I wrote client.php as mentioned here
and server.php as below:
<?php
require_once("lib/nusoap.php");
$host = $_SERVER['HTTP_HOST'];
$miURL = 'http://'.$host.'/WS-Demo';
$server = new nusoap_server();
$server->configureWSDL('L3M_WebService', $miURL);
$server->wsdl->schemaTargetNamespace=$miURL;
$server->register('getDemoData',
array('fldpara' => 'xsd:Array', 'tblpara' => 'xsd:Array', 'cndpara' => 'xsd:Array'),
array('return' => 'xsd:string'),
$miURL);
function decryptRJ256($string_to_decrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$string_to_decrypt = base64_decode($string_to_decrypt);
$rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);
$rtn = rtrim($rtn, "\4");
return($rtn);
}
function encryptRJ256($string_to_encrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);
$rtn = base64_encode($rtn);
return($rtn);
}
function getDemoData($flds, $tbls, $cnds){
$mysqli = new mysqli("localhost", "root", "", "test");
for($i=0;$i< count($flds); $i++) {
$flds[$i] = decryptRJ256($flds[$i]);
}
for($i=0;$i< count($tbls); $i++) {
$tbls[$i] = decryptRJ256($tbls[$i]);
}
for($i=0;$i< count($cnds); $i++) {
$cnds[$i] = decryptRJ256($cnds[$i]);
}
if(! empty($flds)) {
$what = implode(", ", $flds);
} else {
$what = "*";
}
if(! empty($tbls)) {
$from = implode(", ", $tbls);
}else {
$err = 1;
}
if(! empty($cnds)) {
$cond = " WHERE ";
$cond .= $cnds[0] . " = '" . $cnds[1] . "'";
} else {
$cond = "";
}
$sql = "SELECT ".$what." FROM ".$from . $cond;
$rsGetData = $mysqli->query($sql);
$responseData = '<?xml version="1.0" encoding="UTF-8"?>
<L3MDataSets>';
while($rowGetData = $rsGetData->fetch_assoc()) {
$responseData .= '<L3DataSet>';
foreach($rowGetData as $k => $v) {
$responseData .= '<' . $k . '>' . $v . '</' . $k . '>';
}
$responseData .= '</L3DataSet>';
}
$responseData .= '</L3MDataSets>';
$responseData = encryptRJ256($responseData);
$responseString = new soapval('return', 'xsd:string', $responseData );
return $responseData;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
From the Above code in the getDemoData function, if I remove the while loop, it gives the proper output. But when I put back the while loop it shows me output as "-Error: Response not of type text/xml: text/html" even if the SQL query is correct. I have copied and paste the generated SQL query which works in phpMyAdmin.

Styling WordPress's wp_link_pages()

I'm using wp_link_pages() to display pagination, Which looks like:
1
2
3
4
Since this just returns a formatted html string like the above, I find it hard to wrap the current page number in a span to look something like:
<span class="current">1</span>
2
3
4
How to wrap a number surrounded with spaces (sometimes nothing or even <a> tags) in a span tag?
Put this code in functions.php
function custom_wp_link_pages( $args = '' ) {
$defaults = array(
'before' => '<p id="post-pagination">' . __( 'Pages:' ),
'after' => '</p>',`enter code here`
'text_before' => '',
'text_after' => '',
'next_or_number' => 'number',
'nextpagelink' => __( 'Next page' ),
'previouspagelink' => __( 'Previous page' ),
'pagelink' => '%',
'echo' => 1
);
$r = wp_parse_args( $args, $defaults );
$r = apply_filters( 'wp_link_pages_args', $r );
extract( $r, EXTR_SKIP );
global $page, $numpages, $multipage, $more, $pagenow;
$output = '';
if ( $multipage ) {
if ( 'number' == $next_or_number ) {
$output .= $before;
for ( $i = 1; $i < ( $numpages + 1 ); $i = $i + 1 ) {
$j = str_replace( '%', $i, $pagelink );
$output .= ' ';
if ( $i != $page || ( ( ! $more ) && ( $page == 1 ) ) )
$output .= _wp_link_page( $i );
else
$output .= '<span class="current-post-page">';
$output .= $text_before . $j . $text_after;
if ( $i != $page || ( ( ! $more ) && ( $page == 1 ) ) )
$output .= '</a>';
else
$output .= '</span>';
}
$output .= $after;
} else {
if ( $more ) {
$output .= $before;
$i = $page - 1;
if ( $i && $more ) {
$output .= _wp_link_page( $i );
$output .= $text_before . $previouspagelink . $text_after . '</a>';
}
$i = $page + 1;
if ( $i <= $numpages && $more ) {
$output .= _wp_link_page( $i );
$output .= $text_before . $nextpagelink . $text_after . '</a>';
}
$output .= $after;
}
}
}
if ( $echo )
echo $output;
return $output;
}
And call with custom_wp_link_pages()
Source: http://bavotasan.com/2012/a-better-wp_link_pages-for-wordpress/
Why regex as tag ?
You need to use something like:
Page-links in Paragraph Tags
<?php wp_link_pages('before=<p>&after=</p>&next_or_number=number&pagelink=page %'); ?>
Displays page-links wrapped in paragraph tags.
Page-links in DIV
<?php wp_link_pages('before=<div id="page-links">&after=</div>'); ?>
Displays page-links in DIV for CSS reference as <div id="page-links">.
Docs reference : http://codex.wordpress.org/Function_Reference/wp_link_pages

Doctrine2 Iteration

I have the following code for a <select> on a form.
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");`
$groups = $query->iterate();`
$groups_option = "";
foreach( $groups as $row ){
$group = $row[0];
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
}
But this throws an error. What works is...
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
$i = 0;
foreach( $groups as $row ){
$group = $row[$i];
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
$i++;
}
Am I doing something wrong? The reference manual cites the first option as correct...
I found the answer to my own question:
While DQL permits SELECT g.id, g.name without throwing an error, this is actually SQL, not DQL. (Thanks, doctrine reference manual, for being so clear on this...)
The correct way to code this is
$query = $em->createQuery("SELECT partial g.{id,name} FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
foreach( $groups as $group ){
$group = $group[0];
$groups_option .= "<option value=\"{$group->id}\">{$group->name}</option>\n";
}
Your variable names are mismatched.
Remove $group = $row[0] and use foreach ($groups as $group)
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
foreach ( $groups as $group ){
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
}