PHP explode string [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have this string: 0|DY1497ORYOSLDY932OSLCPH|1|0|0
and I need to explode it like that:
0| DY1497 ORY OSL DY932 OSL CPH |1|0|0
$string1 = 'DY1497';
$string2 = 'ORY';
$string3 = 'OSL';
$string4 = 'DY932';
$string5 = 'OSL';
$string6 = 'CPH';
I searched, but all I could find is how to explode when the text is separated with /, -, etc. Any ideas?

The best choice is probably a regex:
if (preg_match('/|(.{6})(.{3})(.{3})(.{5})(.{3})(.{3})|/', $string, $matches)) {
echo $matches[1];
echo $matches[2];
echo $matches[3];
echo $matches[4];
echo $matches[5];
echo $matches[6];
}
This divides the string simply by length in characters. You may need to modify this as needed. See http://regular-expressions.info

I suggest to use substr() if you know the exact position of the characters you need

Son, it looks to me like you searching for some specific tokens up in this here string. What I reckon you can do is, make yerself one array outa little search patterns you might be a looking fer. Something like this here:
$patterns = array('ORY', 'OSL', 'CPH', 'DY[\d]+');
Then you can make yerself a nice big regexp outa that:
$regexp = '/(' . implode('|', $patterns) . ')/';
Then, what you gonna do is, use preg_match_all to find every one of them fellers thisaway:
preg_match_all($regexp, $string, $matches);
Now, you do that and then looka what you got in $matches. I'd wager it has what you need.

Another way of splitting up strings that consists of fixed length fields is with 'unpack' which is very suited to this job.
here is some tested code that demonstrates it:
<?php
$origSource = '0|DY1497ORYOSLDY932OSLCPH|1|0|0';
// expected result
$string1 = 'DY1497';
$string2 = 'ORY';
$string3 = 'OSL';
$string4 = 'DY932';
$string5 = 'OSL';
$string6 = 'CPH';
// get the string we are interested in...
$tempStr = explode('|', $origSource);
$source = $tempStr[1]; // string with fixed length fields
/* debug */ var_dump($source);
// define where the fixed length fields are and the indexes to call them in the output array
$format = 'A6field1/' . 'A3field2/' . 'A3field3/'. 'A5field4/'. 'A3field5/'. 'A*field6/' ; // make it clear where the fields are...
$dest = unpack($format, $source);
/* debug */ var_dump($dest);
?>

firstly you have to concat your string with a special character like -,#,$ etc...
then you can explode it.
after that you may use the following syntax in php to explod string......
<?php
$string= "0|$DY1497$ORY$OSL$DY932$OSL$CPH$|1|0|0";
$pieces = explode("$", $string);
?>
For see your Result:---
<?php
foreach ($pieces as $value)
{
echo "piece: $value<br />";
}
?>
I hope it will help you.

Related

How to clean duplicate BB tags [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
[i][b][i][b](This is a paragraph with BBcode.)[/b][/i][/b][/i]
Some of my BB code has double tags, whats the best way to remove this?
I've tried a few things mostly regex, but I'm honestly a novice when it comes to regex.
This is absolutely horrible, but it works.
<?php
$bb = '[i][b][i][b](This is a paragraph with BBcode.)[/b][/i][/b][/i]';
// regex with start, paragraph, and end capture groups
$regex = '#(?<start>(\[[a-z]*\])*+)(?<paragraph>.*)(?<end>(\[\/[a-z]*\])*+)#U';
// put matches into $matches array
preg_match_all($regex, $bb, $matches);
// get the stuff we need
$start = $matches['start'][0]; // string(12) "[i][b][i][b]"
$paragraph = implode('', $matches['paragraph']);
// now we will grab each tag
$regex = '#\[(?<tag>[a-z])\]#';
preg_match_all($regex, $start, $matches);
$tags = array_unique($matches['tag']);
// and build up the new string
$newString = '';
foreach($tags as $tag) {
$newString .= '[' . $tag . ']';
}
// create the end tags
$end = str_replace('[', '[/', $newString);
// put it all together
$newString .= $paragraph . $end;
echo $newString; // [i][b](This is a paragraph with BBcode.)[/i][/b]
Which gives you [i][b](This is a paragraph with BBcode.)[/i][/b]
Check it here https://3v4l.org/O8UHO
You can try to extract all the tags with a regexp (maybe like /\[.*\]/U) and then iterate throught them, removing all the duplicates
Quick example :
$bb = '[i][b][i][b](This is a paragraph with BBcode.)[/b][/i][/b][/i]';
preg_match_all('/(\[.*\])/gU', $bb, $tags);
$metTags = [];
foreach($tags[0] as $tag) {
// tag has not been met, save it
if (in_array($tag, $metTags) === false) {
$metTags[] = $tag;
// tag have been met already
} else {
// remove it ONCE
$bb = preg_replace('#'.preg_quote($tag).'#', '', $bb, 1);
}
}
echo $bb;
That is probably not the best solution due to preg_replace() use, but still doing the job great.
Edit : add code
So i wrote a long winded method in php only. It basically loops through all the characters, then i when i find an "[" i check the rest for accepted tags. I end up with an array of all the styles and just text allowing me to remove the duplicate styles. Would show code but dont want to get laughed at :D

How to exchange numbers in string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
can you please help me with finding right function for exchanging numbers in string? Numbers are separated with ":".
For example
"2:0" to "0:2"
"101:50" to "50:101"
Thank you.
There are many ways to do it, you can try the any of the ways here.
<?php
//using regex
$re = '/(\d+):(\d+)/i';
$str = '50:101';
$subst = '$2:$1';
$result = preg_replace($re, $subst, $str);
echo "The string $str after exchange is ".$result;
echo PHP_EOL;
// concatenating parts after explode
$parts = explode(':',$str);
echo "The string $str after exchange is $parts[1]:$parts[0]";
echo PHP_EOL;
//using explode, array_reverse and implode
$str = '50:101';
$result = implode(':', array_reverse(explode(':',$str)));
echo "The string $str after exchange is ".$result;
?>
DEMO: https://3v4l.org/OkY18
Simply explode() the string and then reform it.
$str = '100:200';
$bits = explode(':',$str);
echo $bits[1] . ':' . $bits[0];
RESULT
200:100

Search and replace chars in a substring [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Example:
"Hello iam a [start] string and iam very happy with [end] beeing a string...";
Now lets say i only want to change something in the substring between [start] and [end]. I know how to find out the str_pos and the lenght to the end but how can i search and replace something that only affects this substring?
What i want to do is: (for example)
Replace 'x' with 'y' within str positon 5 and 50
I know that there is substr_replace but thats not exactly what iam looking for.
Any ideas would be great, thanks a lot!
If I understand correctly you want to replace something within a substring while knowing it's position within it's parent string. Using substr() and preg_replace can easily do this:
Code:
$str = 'Hello iam a [start] string and iam very happy with [end] beeing a string...';
$begpos = 12; // begin position of [start]
$endpos = 56; // end position of [end]
$substr = substr($str, $begpos, $endpos-$begpos);
$subtit = preg_replace('/\iam/','I AM', $substr);
$newstr = substr_replace($str,$subtit,$begpos,$endpos-$begpos);
echo $newstr;
Result:
Hello iam a [start] string and I AM very happy with [end] beeing a string...
How about something like...
<?php
$string = 'my first word was first then it was the second word';
echo "$string\n";
echo str_pos_replace($string, 'word', 'second', 'first', 'second') . "\n";
function str_pos_replace($string, $start, $end, $find, $replace)
{
$pos1=strpos($string, $start);
$pos2=strpos($string, $end);
$subject=substr($string, $pos1, ($pos2-$pos1));
$replaced=str_replace($find, $replace, $subject);
return str_replace($subject, $replaced, $string);
}
Will print out something like:
my first word was first then it was the second word
my first word was second then it was the second word
here is an example pattern to find the letter 'a' between [start] and [end]
(.*\[start\]|\[end\].*)(*SKIP)(*F)|a
Demo
if is string
str_repalce(needle, replace, haystack)
if array
json_encode haystack
str_replace needle, replace, haystack)
json_decode haystack
Knowing the str position is noit realy of value to you when if you know what you are looking for you can just replace it with some thing else just remember the rule double quotes to use php vars "$haystack" and single quotes will render exactly as you type '$haystack'
this is by far the easyest way and best way to replace text or values in a string or in a array but please read the documentation of the functions before use so you understand how they work. Json_encode / Decode can be a tricky thing to master but once you understand it you can use it to trasform your arrays to strings and back again reall easy.
You could do it with a callback.
Regex:
"/(?xs)^( . {" . $start_pos . "} ) ( . {" . $end_pos . "} )/"
Inside the callback, run a new regex replacement on group 2 for xyz.
Return Catted original group 1 and and the replaced group 2.
Untested code:
$start_pos = 5;
$end_pos = 50;
$str = preg_replace_callback
(
"/(?xs)^( . {" . $start_pos . "} ) ( . {" . $end_pos . "} )/",
function( $matches )
{
$orig_grp1 = $matches[1];
$substr_replaced = preg_replace( '/xyz/', 'XYZ', $matches[2] );
return $orig_grp1 . $substr_replaced;
},
$str
);
So yeah, I was a bit bored, and this might be an overkill, but it does what you ask:
function replaceBetweenTags($needle, $replacement, $haystack, $keepTags = false, $startTag = "[start]", $endTag = "[end]") {
$startPattern = preg_quote($startTag);
$endPattern = preg_quote($endTag);
$pattern = '/'.$startPattern.'(.+)'.$endPattern.'/m';
if (!preg_match($pattern, $haystack)) return $haystack;
return preg_replace_callback($pattern, function($match) use ($startTag, $endTag, $keepTags, $needle, $replacement) {
$match = str_replace($needle, $replacement, $match[0]);
if ($keepTags) return $match;
return str_replace($startTag, "", str_replace($endTag, "", $match));
}, $haystack);
}
Usage is simple:
echo replaceBetweenTags("happy", "sad", "Hello iam a [start] string and iam very happy with [end] beeing a string..."
// Output: Hello iam a string and iam very sad with beeing a string...
// Unless you set $keepTags = true, in which case it'll preserve the tags.
It handles multiple tag pairs too. Things to note:
it's case sensitive
$keepTags = false might leave double spaces. You might want to str_replace those
Hope it helps.

Evaluate a string as PHP code without using eval [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Seeing how eval should be avoided, how do you evaluate a string as PHP code without using eval? For example consider this code:
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
$str = "\"$str\""; // Now I have a string with double quotes around it.
// how to get the contents of $str evaluated without using eval()
?>
I can get the desired result by using eval like so - eval("echo $str;");, but eval is exactly what I am looking to avoid.
You might view this as a question of removing the double quotes. But it isn't about that. As #AmalMurali points out, what I am asking here is how to get the contents of $str evaluated without using eval()
You can layout your code like this:
$string = 'cup';
$name = 'coffee';
$str = 'This is a ' . $string . ' with my ' . $name . ' in it.';
Or perhaps like this, using sprintf which is my personal favorite method of handling cases like this:
$string = 'cup';
$name = 'coffee';
$str = sprintf('This is a %s with my %s in it.', $string, $name);
There are different options based on personal style & preference.
What you really want here is to use double quotes for $str so that variable replacement can take place.
See also the docs: http://www.php.net/manual/it/language.types.string.php#language.types.string.syntax.double
Why are you adding double quotes then removing them? For a simple string variable inclusion you just use double quotes like
$string = 'cup';
$name = 'coffee';
$str = "This is a $string with my $name in it.";
echo $str;

Reverse Order of String like "Hello Word" reverse as "Word Hello" in PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need to reverse String "Hello Word" into "Word Hello", it could be "My Name is Khan" reverse into "Khan is Name My" in PHP
$str = "My Name is Khan";
$reverse = implode(" ",array_reverse(explode(" ", $str)));
echo $reverse;
Result is Khan is Name My.
explode splits the string into an array in accordance to the delimiter, which in this case is " ". array_reverse is self-explanatory, it reverses the order of the array. implode then joins the string using the delimiter.
You might think to code something to show then let us help you with the answer, but let me describe the logic, since you are going to input it as a string, you might think to split the character based on the character you wanted to split
you might consider this EXPLODE
After you finish and put that split into an array. You can reverse it back using looping or perhaps you want to reverse using THIS
$string = "My Name is Khan";
$new = explode(' ', $string);
$new = array_reverse($new);
print_r(implode(' ', $new));
At first, requirement is: reverse the order of words not alphabets.
So, need to split the string by spaces(as words are separated by spaces).
This way, an array is generated like:
array('World', 'Hello');
Change the sequence of array using array_reverse()
The resulting array would be:
array('Hello', 'World');
Now, again join the above array by space:
The resulting string would be:
Hello World
Try this:
<?php
$name = 'World Hello';
$temp = explode(' ', $name);
echo '<pre>';
print_r($temp);
echo '</pre>';
$arr = array_reverse($temp);
echo '<pre>';
print_r($arr);
echo '</pre>';
$str = implode(' ', $arr);
echo $str;
?>

Categories