PHP : How to select specific parts of a string [duplicate] - php

This question already has answers here:
Extract a substring between two characters in a string PHP
(11 answers)
Closed 10 months ago.
I was wondering... I have two strings :
"CN=CMPPDepartemental_Direction,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan",
"CN=CMPPDepartemental_Secretariat,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan"
Is there a way in php to select only the first part of these strings ? I would like to just select CMPPDepartemental_Direction and CMPPDepartemental_Secretariat.
I had thought of trying with substr() or trim() but without success.

You should use preg_match with regex CN=(\w+_\w+) to extract needed parts:
$strs = [
"CN=CMPPDepartemental_Direction,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan",
"CN=CMPPDepartemental_Secretariat,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan"
];
foreach ($strs as $str) {
$matches = null;
preg_match('/CN=(\w+_\w+)/', $str, $matches);
echo $matches[1];
}

If the strings always have the same structure, I recommend using a custom function find_by_keyword - so you can search for other keywords too.
function find_by_keyword( $string, $keyword ) {
$array = explode(",",$string);
$found = [];
// Loop through each item and check for a match.
foreach ( $array as $string ) {
// If found somewhere inside the string, add.
if ( strpos( $string, $keyword ) !== false ) {
$found[] = substr($string, strlen($keyword));
}
}
return $found;
}
var_dump(find_by_keyword($str2, "CN="));
// array(1) {
[0]=>
string(27) "CMPPDepartemental_Direction"
}
var_dump(find_by_keyword($str2, "OU="));
//array(4) {
[0]=>
string(25) "1 - Groupes de sécurité"
[1]=>
string(4) "CMPP"
[2]=>
string(4) "Pole"
[3]=>
string(12) "Utilisateurs"
}
Examle here.

Related

Howto format php array values & insert them into database [duplicate]

This question already has answers here:
Converting a number with comma as decimal point to float
(9 answers)
str_pad with a float in php?
(2 answers)
Remove non-numeric characters (excluding periods and commas) from a string (i.e. remove all characters except numbers, commas, and periods)
(5 answers)
Closed 3 years ago.
This is my code where I read csv file (which I get from the bank), parsing it into array & insert it into database:
$csvFile = file('tecajnica.csv');
$keys = str_getcsv(array_shift($csvFile), ';');
foreach ($csvFile as $csvRecord) {
// combine our $csvRecord with $keys array
$csv[] = array_combine($keys, str_getcsv($csvRecord, ';'));
}
foreach( $csv as $row) {
$db2 = new PDO ("odbc:as400");
$sqlf93p = $db2->prepare("INSERT INTO..... VALUES (".$row['sifra'].",".$row['Kupovni2']." ......)
$sqlf93p->execute();
This is how my array looks like:
[0]=>
array(10) {
["id"]=>
string(2) "67"
["drzava"]=>
string(10) "Australija"
["sifra"]=>
string(7) "036 AUD"
["VrijediZa"]=>
string(1) "1"
["Kupovni1"]=>
string(8) "4,5207"
["Kupovni2"]=>
string(8) "4,589597"
}
[1]=>
array(10) {
["id"]=>
string(0) ""
["drzava"]=>
string(5) "Ceska"
["sifra"]=>
string(7) "203 CZK"
["VrijediZa"]=>
string(1) "1"
["Kupovni1"]=>
string(8) "0,277098"
["Kupovni2"]=>
string(8) "0,2821"
}
* * * * * * * etc * * * * * *
So my questions are:
1) Howto convert ["sifra"]=> "203 CZK" to ["sifra"]=> "203" (I want only numeric value to appear before insert)?
2) Howto convert ["Kupovni2"]=> "0,2821" to ["Kupovni2"]=> "0,282100" (I want 6 decimal places before insert)?
Thanks.
Another option could be to replace all non digits using \D+ with an empty string.
$digitsOnly = preg_replace('/\D+/', '', "203 CZK");
echo $digitsOnly; // 203
For appending the zeroes, you might use str_pad:
$parts = explode(',', '0,2821');
$str = implode(',', [$parts[0], str_pad($parts[1], 6, '0', STR_PAD_RIGHT)]);
echo $str; // 0,282100
Php demo
Your code might look like:
foreach( $csv as $row) {
$db2 = new PDO ("odbc:as400");
$sifra = preg_replace('/\D+/', '', $row['sifra']);
$parts = explode(',', $row['Kupovni2']);
$kupovni2 = implode(',', [$parts[0], str_pad($parts[1], 6, '0', STR_PAD_RIGHT)]);
$sqlf93p = $db2->prepare("INSERT INTO..... VALUES (". $sifra . "," . $kupovni2 ." ......);
$sqlf93p->execute();
To get number from a string you can do it this way
$string = '203 CZK';
echo (int) $string;
OR
$string = '203 CZK';
echo filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
To make string to length 8 you can use str_pad
$string = '0,2821';
echo str_pad($string, 8, "0", STR_PAD_RIGHT);
Result :-
0,282100

PHP break string into two parts

Note: I can't use break or next line functions as i am using FPDF
I am having a problem with php strings. I am having a string where i want to show atmost 12 characters in first row and remaining in second row. So basically i want to break string into two parts and assign to two variables so that i can print those two variables. I have tried following code :-
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 12);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
But using this I am getting as shown below :
Original String : The Best Hotel Ever
Output :
The Best Hot
Tel Ever
It is breaking a word, i don't want to break the word, just check the length and if within 12 characters all the words are complete then print next word in next line. Like this :
Desired OutPut:
The Best
Hotel Ever
Any suggestions ?
I see no built-in function to do it, however you could explode on spaces, and re-build your string until the length with the next words get over 12, everything else going to the second part :
$string = 'The Best Hotel Ever';
$exp = explode(' ', $string);
if (strlen($exp[0]) < 12) {
$tmp = $exp[0];
$i = 1;
while (strlen($tmp . ' ' . $exp[$i]) < 12) {
$tmp .= " " . $exp[$i];
$i++;
}
$array[0] = $tmp;
while (isset($exp[$i])) {
$array[1] .= ' ' . $exp[$i];
$i++;
}
$array[1] = trim($array[1]);
} else {
$array[0] = '';
$array[1] = trim(implode (' ', $exp));
}
var_dump($array);
// Output : array(2) { [0]=> string(8) "The Best" [1]=> string(10) "Hotel Ever" }
// $string1 = 'The';
// array(2) { [0]=> string(3) "The" [1]=> string(0) "" }
// $string2 = 'Thebesthotelever';
// array(2) { [0]=> string(0) "" [1]=> string(16) "Thebesthotelever" }
Im not too crash hot on PHP but it seems to be a simple case of which element of the string you are accessing is futher across from where you want to be:
Try:
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 8);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
For further help check out because you need to remember to count from zero up:
http://php.net/manual/en/function.substr.php

get values using regular expression and preg_match_all

I have string data
$pages = "mangaName=&authorArtist=asdas123s&genres=sn&genres[23]=on&genres[29]=on&status=&chrome=&submit=+";
function get_h1($file){
$h1tags = preg_match_all('/\[(\w*)\]/is',$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return $res;
}
i want get number on genres[23] , genres[29]
[0] => 23
[1] => 29
$pages = "mangaName=&authorArtist=asdas123s&genres=sn&genres[23]=on&genres[29]=on&status=&chrome=&submit=+";
parse_str($pages, $parsed);
var_dump(array_keys($parsed['genres'])); // array(2) { [0]=> int(23) [1]=> int(29) }
zerkms' answer is the right one, but if you really want to use regexp, change yours with this one:
preg_match_all('/\[(\w*?)\]/is',$file,$patterns);
note the non-greedy __^

Split long string into little ones. - trying to find an elegant way for doing so

If the string is bigger then 50 chars long, I need to split it.
The maximum allowed is 3 chunks of 50. It could be less then 50 but never more then 150.
I don't need any special chars to be added, or to serve as "splitters"; I can break the string anywhere, no problem, since the propose is not for showing it to the user.
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
}
Is there a more elegant way for doing this?
UPDATE:
An example of what would arrive next:
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
if(!empty($streetPart2) && empty($streetPart3)
{
//add part2 only.
}elseif(!empty($streetPart2 && !empty($streetPart3))
{
//add part 2 and part 3
}
}
Thanks a lot.
MEM
You may simply use str_split:
$parts = str_split($string, 50);
// if you want to have vars instead of array:
list($part1, $part2, $part3) = str_split($string, 50);
Check the PHP's wordwrap() function.
http://php.net/manual/en/function.wordwrap.php
And check out the explode() function
http://php.net/manual/en/function.explode.php
<?
function wrapAndCropToArray($text, $width, $lines)
{
$ret = array_slice(
explode("\n",wordwrap($text,$width,"\n",true))
, 0
, $lines+1
);
if(isset($ret[$lines]))
$ret[$lines] = "...";
return $ret;
}
$test = "aadfuiosdy 34 123 412 341f2 38947 1029 384h120 39uh4 19023h 41234";
var_dump(wrapAndCropToArray($test,10,3));
?>
Will output:
array(4) {
[0]=>
string(10) "aadfuiosdy"
[1]=>
string(10) "34 123 412"
[2]=>
string(5) "341f2"
[3]=>
string(3) "..."
}

UTF-8 characters in preg_match_all (PHP) [duplicate]

This question already has answers here:
preg_match and UTF-8 in PHP
(8 answers)
Closed 12 months ago.
I have preg_match_all('/[aäeëioöuáéíóú]/u', $in, $out, PREG_OFFSET_CAPTURE);
If $in = 'hëllo' $out is:
array(1) {
[0]=>
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "ë"
[1]=>
int(1)
}
[1]=>
array(2) {
[0]=>
string(1) "o"
[1]=>
int(5)
}
}
}
The position of o should be 4. I've read about this problem online (the ë gets counted as 2). Is there a solution for this? I've seen mb_substr and similar, but is there something like this for preg_match_all?
Kind of related: Is their an equivalent of preg_match_all in Python? (Returning an array of matches with their position in the string)
This is not a bug, PREG_OFFSET_CAPTURE refers to the byte offset of the character in the string.
mb_ereg_search_pos behaves the same way. One possibility is to change the encoding to UTF-32 before and then divide the position by 4 (because all unicode code units are represented as 4-byte sequences in UTF-32):
mb_regex_encoding("UTF-32");
$string = mb_convert_encoding('hëllo', "UTF-32", "UTF-8");
$regex = mb_convert_encoding('[aäeëioöuáéíóú]', "UTF-32", "UTF-8");
mb_ereg_search_init ($string, $regex);
$positions = array();
while ($r = mb_ereg_search_pos()) {
$positions[] = reset($r)/4;
}
print_r($positions);
gives:
Array
(
[0] => 1
[1] => 4
)
You could also convert the binary positions into code unit positions. For UTF-8, a suboptimal implementation is:
function utf8_byte_offset_to_unit($string, $boff) {
$result = 0;
for ($i = 0; $i < $boff; ) {
$result++;
$byte = $string[$i];
$base2 = str_pad(
base_convert((string) ord($byte), 10, 2), 8, "0", STR_PAD_LEFT);
$p = strpos($base2, "0");
if ($p == 0) { $i++; }
elseif ($p <= 4) { $i += $p; }
else { return FALSE; }
}
return $result;
}
There is simple workaround, to be used after preg_match() results matched. You need to iterate every match result and reassign position value with following:
$utfPosition = mb_strlen(substr($wholeSubjectString, 0, $capturedEntryPosition), 'utf-8');
Tested on php 5.4 under Windows, depends on Multibyte PHP extension only.
PHP doesn't support unicode very well, so a lot of string functions, including preg_*, still count bytes instead of characters.
I tried finding a solution by encoding and decoding strings, but ultimately it all came down to the preg_match_all function.
About the python thing: a python regex matchobject contains the match position by default mo.start() and mo.end(). See: http://docs.python.org/library/re.html#finding-all-adverbs-and-their-positions
Another way how to split UTF-8 $string by a regular expression is to use function preg_split(). Here is my working solution:
$result = preg_split('~\[img/\d{1,}/img\]\s?~', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
PHP 5.3.17

Categories