How can I get all text after a given phrase? - php

How can I get everything from $string after "<div class='partFive'>"?

try this,
$prefix = "<div class='partFive'>";
$index = strpos($string, $prefix) + strlen($prefix);
$result = substr($string, $index);
obviously you don't have to re-calculate the "strlen" part of it each time if the $prefix value is static.

$myString = strstr($string, "<div class='partFive'>");

Do you need everything after <div class='partFive'> or everything in that DOM element?
I'm assuming you mean you want to grab everything in that DOM element, and the easiest way would be to grab it by using Zend_Dom.
$dom = new Zend_Dom_Query($html);
$results = $dom->query('div.partFive');
foreach ($results as $result) {
// $result is a DOMElement
}

You could just remove the part you don't want, like so:
$myString = str_replace("<div class='partFive'>","",$string);

Related

Can not to replace string

The problem is related to php. I have a text in a variable say $text and some start position and end positions. How to inject the some substring on the specific position. the problem is that if i put some text in a specific position then position index changes and it will be difficult to put next sub string to the right place. Help me. thanks in advance.
function previewTxt($text,$topicid, $sectionid)
{
$dbConn = new DBConnUtil();
$queryString = "SELECT * from inline_topic_xref where TOPIC_ID=$topicid and SECTION_ID=$sectionid";
$result = $dbConn->run_query($queryString);
$newtext=$text;
$count=0;
while($row = $result->fetch_object())
{
$newtext = replace($newtext, "<a href='#'>" ,$row->REF_TEXT_START);
$newtext = replace($newtext, "</a>" ,$row->REF_TEXT_END);
}
return $newtext;
}
function replace($org_text,$str_rep, $position)
{
$length=strlen($org_text);
$temp1=substr($org_text,0,$position);
$temp2=substr($org_text,$position,$length);
$replaced =$temp1.$str_rep.$temp2;
return $replaced;
}
have you tried
substr_replace($oldstr, $str_to_insert, $pos, 0)
?
here is the documentation
http://php.net/manual/en/function.substr-replace.php

Combining two php codes

So right now I have 2 php codes that work exactly as they are supposed to
the first one pulls all info from the "src" of an "img" tag
<?php
$url="foo";
$html = file_get_contents($url);
$doc = new DOMDocument();
#$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
echo $tag->getAttribute('src') . "<br>";
}
?>
the second one is designed to pull a string of characters from between two others strings
<?php
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
?>
what I need is to figure out how to use the second code to only pull a piece of the "src" and replace it for as long as there are still "img" tags to process
so if the tag comes back "/pics/foo.jpg" i can remove the "/pics/" and the ".jpg" leaving me with just "foo"
i hope i have made some sense. thanks
Why do you want to use the second code? You can do it with exploding the fullstring:
$exploded_tag = explode($tag,'\');
Then you need the last element of the string (foo.jpg):
$last_part = end($exploded_tag);
Then you have to explode it and take the first element (foo):
$exploded_lastpart = explode($last_part,'.');
$piece = $exploded_lastpart[0];
You don't need second code. There is function in PHP called pathinfo(). So you can just do:
$path_parts = pathinfo('/pics/foo.jpg');
echo $path_parts['filename'];

PHP "preg_replace" to add query param to any urls of a certain domain

I have a string like:
$description = '
1st link in string,
2nd link in string, some other text in string,
3rd link in string.
';
I need to use preg_replace to append a query parameter of "?id=awesome" to any urls in the $description string from "replace.com" (ignoring all other links, i.e. "ignore.com").
Thanks in advance for any help!
I would strongly advise using a DOM parser instead of a regex. For instance:
$description = '...';
$wrapper = "<root>".$description."</root>";
$dom = new DOMDocument();
$dom->loadXML($wrapper);
$links = $dom->getElementsByTagName('a');
$count = $links->length;
for( $i=0; $i<$count; $i++) {
$link = $links->item($i);
$href = $link->getAttribute("href");
if( preg_match("(^".preg_quote("http://www.replace.com/").")i",$href))
$link->setAttribute("href",$href."?id=awesome");
}
$out = $dom->saveXML();
$result = substr($out,strlen("<root>"),-strlen("</root>"));
Ok, simple enough, here you go:
$content = preg_replace('/http:\/\/[^"]*?\.replace\.com\/[^"]+/','$0?id=awesome',$description);
Hope that's it, $content will have the string witht he added paramters to the replace.com domain :)

How to get the value of the href attribute?

With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:
a wrong one
the right one
a wrong one
That is, to get the value of the href attribute if the link has a particular text.
This will select the attributes:
"//a[text()='the right one']/#href"
i think this is the best solution, you can use each of them as an array element
$String= '
a wrong one
the right one
a wrong one
';
$array=get_all_string_between($String,'href="','">');
print_r($array);//just to see what is inside the array
//now get each of them
foreach($array as $value){
echo $value.'<br>';
}
function get_all_string_between($string, $start, $end)
{
$result = array();
$string = " ".$string;
$offset = 0;
while(true)
{
$ini = strpos($string,$start,$offset);
if ($ini == 0)
break;
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
$result[] = substr($string,$ini,$len);
$offset = $ini+$len;
}
return $result;
}
"//a[#href='http://example.com']"
I'd use an opensource class like simple_html_dom.php
$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
echo $oElement->href
}
Here's a full example using SimpleXML:
$xml = '<html>a wrong one'
. 'the right one'
. 'a wrong one</html>';
$tree = simplexml_load_string($xml);
$nodes = $tree->xpath('//a[text()="the right one"]');
$href = (string) $nodes[0]['href'];

php associative arrays, regex, array

I currently have the following code :
$content = "
<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";
I need to find a method to create and array as name=>value. E.g Manufacturer => John Deere.
Can anyone help me with a simple code snipped I tried some regex but doesn't even work to extract the names or values, e.g.:
$pattern = "/<name>Manufacturer<\/name><value>(.*)<\/value>/";
preg_match_all($pattern, $content, $matches);
$st_selval = $matches[1][0];
You don't want to use regex for this. Try out something like SimpleXML
EDIT
Well, why don't you start with this:
<?php
$content = "<root>" . $content . "</root>";
$xml = new SimpleXMLElement($c);
print_r($xml);
?>
EDIT 2
Despite the fact that some of the answers posted using regular expression MAY work, you should get in the habit of using the correct tool for the job and regular expressions are not the correct tool for parsing of XML.
I'm using your $content variable:
$preg1 = preg_match_all('#<name>([^<]+)#', $content, $name_arr);
$preg2 = preg_match_all('#<value>([^<]+)#', $content, $val_arr);
$array = array_combine($name_arr[1], $val_arr[1]);
This is rather simple, can be solved by regex. Should be:
$name = '<name>\s*([^<]+)</name>\s*';
$value = '<value>\s*([^<]+)</value>\s*';
$pattern = "|$name $value|";
preg_match_all($pattern, $content, $matches);
# create hash
$stuff = array_combine($matches[1], $matches[2]);
# display
var_dump($stuff);
Regards
rbo
First of all, never use regex to parse xml...
You could do this with an XPATH query...
First, wrap the content in a root tag to make the parser happy (if it doesn't already have it):
$content = '<root>' . $content . '</root>';
Then, load the document
$dom = new DomDocument();
$dom->loadXml($content);
Then, initialize the XPATH
$xpath = new DomXpath($dom);
Write your query:
$xpathQuery = '//name[text()="Manufacturer"]/follwing-sibling::value/text()';
Then, execute it:
$manufacturer = $xpath->evaluate($xpathQuery);
If I did the xpath right, it $manufacturer should be John Deere...
You can see the docs on DomXpath, a basic primer on XPath, and a bunch of XPath examples...
Edit: That won't work (PHP doesn't support that syntax (following-sibling). You could do this instead of the xpath query:
$xpathQuery = '//name[text()="Manufacturer"]';
$elements = $xpath->query($xpathQuery);
$manufacturer = $elements->item(0)->nextSibling->nodeValue;
I think this is what you're looking for:
<?php
$content = "<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";
$pattern = "(\<name\>(\w*)\<\/name\>\<value\>(\w*)\<\/value\>)";
preg_match_all($pattern, $content, $matches);
$arr = array();
for ($i=0; $i<count($matches); $i++){
$arr[$matches[1][$i]] = $matches[2][$i];
}
/* This is an example on how to use it */
echo "Location: " . $arr["Location"] . "<br><br>";
/* This is the array */
print_r($arr);
?>
If your array has a lot of elements dont use the count() function in the for loop, calculate the value first and then use it as a constant.
I'll edit as my PHP is wrong, but here's some PHP (pseudo-)code to give some direction.
$pattern = '|<name>([^<]*)</name>\s*<value>([^<]*)</value>|'
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
for($i = 0; $i < count($matches); $i++) {
$arr[$matches[$i][1]] = $matches[$i][2];
}
$arr is the array you want to store the name/value pairs.
Using XMLReader:
$content = '<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>';
$content = '<content>' . $content . '</content>';
$output = array();
$reader = new XMLReader();
$reader->XML($content);
$currentKey = null;
$currentValue = null;
while ($reader->read()) {
switch ($reader->name) {
case 'name':
$reader->read();
$currentKey = $reader->value;
$reader->read();
break;
case 'value':
$reader->read();
$currentValue = $reader->value;
$reader->read();
break;
}
if (isset($currentKey) && isset($currentValue)) {
$output[$currentKey] = $currentValue;
$currentKey = null;
$currentValue = null;
}
}
print_r($output);
The output is:
Array
(
[Manufacturer] => John Deere
[Year] => 2001
[Location] => NSW
[Hours] => 6320
)

Categories