I'm searching a function to cut the following string and get all content BEFORE and AFTER
I need this part<!-- more -->and also this part
Result should be
$result[0] = "I need this part"
$result[1] = "and also this part"
Appreciate any help!
Use the explode() function in PHP like this:
$string = "I need this part<!-- more -->and the other part.
$result = explode('<!-- more -->`, $string) // 1st = needle -> 2nd = string
Then you call your result:
echo $result[0]; // Echoes: I need that part
echo $result[1]; // Echoes: and the other part.
You can do this pretty easily with regular expressions. Somebody out there is probably crying for parsing HTML/XML with regular expressions, but without much context, I'm going to give you the best that I've got:
$data = 'I need this part<!-- more -->and also this part';
$result = array();
preg_match('/^(.+?)<!--.+?-->(.+)$/', $data, $result);
echo $result[1]; // I need this part
echo $result[2]; // and also this part
If you are parsing HTML, considering reading about parsing HTML in PHP.
Use preg_split. Maybe something like this:
<?php
$result = preg_split("/<!--.+?-->/", "I need this part<!-- more -->and also this part");
print_r($result);
?>
Outputs:
Array
(
[0] => I need this part
[1] => and also this part
)
Related
Hi I am replacing certain names with different value . Here is values I am replacing "#size-name" and "#size" .But the problem is my code replacing only size first and note name for example
#size = "replaceword"
#size-name = "replaceword2"
But its replacing
#size ="replaceword"
#size-name = "replaceword2-name"
How can I replace whole word not part of it here is my code
$tempOutQuery = preg_replace("/(\b($key)\b)/i" , $value , $tempOutQuery);
$tempOutQuery= str_replace("#".$key ,$value ,$tempOutQuery);
both codes are not working
My Full Code
$val= "Hi I want #size dress which is #size-name";
$tempOutQuery = preg_replace("/(\b(size)\b)/i" ,"replaceword", $tempOutQuery);
$tempOutQuery = preg_replace("/(\b(size-name)\b)/i" ,"replaceword2", $tempOutQuery);
If you could make replace without using regulat expressions, then I would suggest using standart str_replace() with arrays:
$val= "Hi i want #size dress which is #size-name";
$search = array('size-name', 'size');
$replace = array('replaceword2', 'replaceword');
$result = str_replace($search, $replace, $val);
The order of search and replace Strings is important!
You should take care that you replace long search-strings first, and the short strings later.
Here's another option for you, using preg_replace_callback. It's actually very similar to Gennadiy's method. The only real difference is that it's using the preg aspect of PHP (and it's a lot more work). But it's another way to skin the proverbial cat.
<?php
// SET OUR DEFAULT STRING
$string = 'Hi I want #size suit which is #size-name';
// LOOK FOR EITHER size-name OR size AND IF YOU FIND IT ...
// RUN THE FUNCTION 'replace_sizes'
$string = preg_replace_callback('~#(size-name|size)~', 'replace_sizes', $string);
// PRINT OUT OUR MODIFIED STRING
print $string;
// THIS IS THE FUNCTION THAT WILL BE RUN EVERY TIME A MATCH IS FOUND
// EITHER 'size' OR 'size-name' WILL BE STORED IN $m[1]
function replace_sizes($m) {
// SET UP AN ARRAY THAT HAS OUR POTENTIAL MATCHES AS KEYS
// AND THE TEXT WE WANT TO REPLACE WITH AS THE VALUE
$size_text_array = array('size-name' => 'replaceword2', 'size' => 'replaceword');
// RETURN WHATEVER THE VALUE IS BASED ON THE KEY
return $size_text_array[$m[1]];
}
This will print out:
Hi I want replaceword suit which is replaceword2
Here is a working demo:
http://ideone.com/njNTbB
You can try pre_replace() to replace whole word from an item of an array in PHP a shown below.
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\band\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
See the entire post here
I'm trying to split a php string in to parts the first one include the delimiter but the second one doesn't
$string = "abc==123";
What I want exactly is to get
$string['0'] = "abc==";
$string['1'] = "123";
Thanks for help
Simple enough
<?php
$string = explode("==", $string);
$string[0] .= "==";
?>
I believe you want the function strstr
http://us1.php.net/strstr
You can use PHP's explode function,
$data = "abc==123";
$result = explode("==", $data);
echo $result[0]. "==";
echo $result[1];
what is the best way of extracting multiple (~40 values) from a text file using php?
the data is more or less like:
NAMEA valuea
NAMEB valueb
I'm looking for a proper* approach to extracting this data into a data-structure, because i will need to specify regexs for all of them (all 40).
did i make myself clear?
*meaning, the default/painful method would be for me to do:
$namea = extractfunction("regexa", $textfilevalue);
$nameb = extractfunction("regeb", $textfilevalue);
... 40 times!
The lines may not be in the same order, or be present in each file. Every NAMEA is text like: "Registration Number:", or "Applicant Name:" (ie, with spaces in what i was calling as NAMEA)
Response to the Col.
i'm looking for a sensible "way" of writing my code, so its readable, modifiable, builds an object/array thats easily callable, etc... "good coding style!" :)
#Adam - They do actually... and contain slashes as well...
#Alix - Freaking marvelous man! THat was GOOD! would you also happen to have any insights on how I can "truncate" the rsultant array by removing everything from "key_x" and beyond? Should i open that as a new question?
Here is my take at it:
somefile.txt:
NAMEA valuea
NAMEB valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = preg_replace('~^(.+?)\s+(.+?)$~m', '$1=$2', $file);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[NAMEA] => valuea
[NAMEB] => valueb
)
You may also be able to further simplify this by using str_getcsv() on PHP 5.3+.
EDIT: My previous version fails for keys that have spaces like #Col. Shrapnel noticed. I didn't read the question with enough attention. A possible solution since you seem to be using keys that always have : appended is this:
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $file);
To remove everything from key_x to the end of the file you can do something like this:
$string = substr($string, 0, strpos($string, 'key_x'));
So the whole thing would look like this:
somefile.txt:
Registration Number: valuea
Applicant Name: valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = substr($file, 0, strpos($file, 'key_x'));
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $string);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[Registration_Number] => valuea
[Applicant_Name] => valueb
)
as far as I get it you can use file() to get an array of strings and then parse these strings with some regexp.
if you add a = sign between names and values, you'll be ble to get the whole thing at once using parse_ini_file()
Assuming your keys (namea, nameb) never have spaces in them:
$contents = file('some_file.txt'); // read file as array
$data = array();
foreach($contents as $line) { // iterate over file
preg_match('/^([^\s]+)\s+(.*)/', $line, $matches); // pull out key and value into $matches
$key = $matches[1];
$value = $matches[2];
$data[$key] = $value; // store key/value pairs in $data array
}
var_dump($data); // what did we get?
What I'm trying to do is very simple, but I'm looking to do it most efficiently, preferably using php builtin fns.
$str = '1234';
echo replace_function(array('1','3'),array('3','1'),$str);
// output: 3214
str_replace,preg_replace would result in 1214, which means it goes through the arrays, replacing matched strings. I'm looking for a solution to simultaneously "switch" these two (or more) strings.
any ideas?
You need string translate:
http://php.net/manual/en/function.strtr.php
<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
// = hello all, I said hi
?>
<?php
$subject = '1234';
$result = preg_replace('/(1)(2)(3)(4)/si', '$3$2$1$4', $subject);
var_dump($result);
?>
You can change the pattern to something more generic, such as '/(\d)(\d)(\d)(\d)/'.
I have a string, for example "[{XYZ123}] This is a test" and need to parse out the content in between the [{ and }] and dump into another string. I assume a regular expression is in order to accomplish this but as it's not for the faint of heart, I did not attempt and need your assistance.
What is the best way to pull the fragment in between the [{ and }]? Thanks in advance for your help!
<?php
$str = "[{XYZ123}] This is a test";
if(preg_match('/\[{(.*?)}\]/',$str,$matches)) {
$dump = $matches[1];
print "$dump"; // prints XYZ123
}
?>
$str = "[{XYZ123}] This is a test";
$s = explode("}]",$str);
foreach ($s as $k){
if ( strpos($k,"[{") !==FALSE ){
$t = explode("[{",$k); #or use a combi of strpos and substr()
print $t[1];
}
}
The regex would be (?=\[\{).*(?=\}\]), though I don't know if php supports look aheads.